Java2实用教程(第二版)程序代码——第二十一章 Java网络的基本知识
1//例子1
2import java.applet.*;import java.awt.*;
3import java.awt.event.*;import java.net.*;
4public class Example21_1 extends Applet implements ActionListener
5{ Button button;
6 URL url;
7 TextField text;
8 public void init()
9 { text=new TextField(18);
10 button=new Button("确定");
11 add(new Label("输入网址:"));add(text); add(button);
12 button.addActionListener(this);
13 }
14 public void actionPerformed(ActionEvent e)
15 { if(e.getSource()==button)
16 { try { url=new URL(text.getText().trim());
17 getAppletContext().showDocument(url);
18 }
19 catch(MalformedURLException g)
20 { text.setText("不正确的URL:"+url);
21 }
22 }
23 }
24}
25
26//例子2
27(1)客户端程序:
28import java.io.*;
29import java.net.*;
30public class Client
31{ public static void main(String args[])
32 { String s=null;
33 Socket mysocket;
34 DataInputStream in=null;
35 DataOutputStream out=null;
36 try{
37 mysocket=new Socket("localhost",4331);
38 in=new DataInputStream(mysocket.getInputStream());
39 out=new DataOutputStream(mysocket.getOutputStream());
40 out.writeUTF("你好!");//通过 out向"线路"写入信息。
41 while(true)
42 {
43 s=in.readUTF();//通过使用in读取服务器放入"线路"里的信息。堵塞状态,
44 //除非读取到信息。
45 out.writeUTF(":"+Math.random());
46 System.out.println("客户收到:"+s);
47 Thread.sleep(500);
48 }
49 }
50 catch(IOException e)
51 { System.out.println("无法连接");
52 }
53 catch(InterruptedException e){}
54 }
55}
56(2)服务器端程序:
57import java.io.*;import java.net.*;
58public class Server
59{ public static void main(String args[])
60 { ServerSocket server=null;
61 Socket you=null;String s=null;
62 DataOutputStream out=null;DataInputStream in=null;
63 try{ server=new ServerSocket(4331);}
64 catch(IOException e1){System.out.println("ERRO:"+e1);}
65 try{ you=server.accept();
66 in=new DataInputStream(you.getInputStream());
67 out=new DataOutputStream(you.getOutputStream());
68 while(true)
69 {
70 s=in.readUTF();// 通过使用in读取客户放入"线路"里的信息。堵塞状态,
71 //除非读取到信息。
72
73 out.writeUTF("你好:我是服务器");//通过 out向"线路"写入信息.
74 out.writeUTF("你说的数是:"+s);
75 System.out.println("服务器收到:"+s);
76 Thread.sleep(500);
77 }
78 }
79 catch(IOException e)
80 { System.out.println(""+e);
81 }
82 catch(InterruptedException e){}
83 }
84}
85
86//例子3
87 (1) 客户端
88import java.net.*;import java.io.*;
89import java.awt.*;import java.awt.event.*;
90import java.applet.*;
91public class Computer_client extends Applet implements Runnable,ActionListener
92{ Button 计算;TextField 输入三边长度文本框,计算结果文本框;
93 Socket socket=null;
94 DataInputStream in=null; DataOutputStream out=null;
95 Thread thread;
96 public void init()
97 { setLayout(new GridLayout(2,2));
98 Panel p1=new Panel(),p2=new Panel();
99 计算=new Button(" 计算");
100 输入三边长度文本框=new TextField(12);计算结果文本框=new TextField(12);
101 p1.add(new Label("输入三角形三边的长度,用逗号或空格分隔:"));
102 p1.add( 输入三边长度文本框);
103 p2.add(new Label("计算结果:"));p2.add(计算结果文本框);p2.add(计算);
104 计算.addActionListener(this);
105 add(p1);add(p2);
106 }
107 public void start()
108 { try
109 { //和小程序所驻留的服务器建立套接字连接:
110 socket = new Socket(this.getCodeBase().getHost(), 4331);
111 in =new DataInputStream(socket.getInputStream());
112 out = new DataOutputStream(socket.getOutputStream());
113 }
114 catch (IOException e){}
115 if(thread == null)
116 { thread = new Thread(this);
117 thread.start();
118 }
119 }
120 public void run()
121 { String s=null;
122 while(true)
123 { try{ s=in.readUTF();//堵塞状态,除非读取到信息。
124
125 计算结果文本框.setText(s);
126 }
127 catch(IOException e)
128{ 计算结果文本框.setText("与服务器已断开");
129 break;
130}
131 }
132 }
133 public void actionPerformed(ActionEvent e)
134 { if(e.getSource()==计算)
135 { String s=输入三边长度文本框.getText();
136 if(s!=null)
137 { try { out.writeUTF(s);
138 }
139 catch(IOException e1){}
140 }
141 }
142 }
143}
144
145 (2) 服务器端
146import java.io.*;import java.net.*;
147import java.util.*;import java.sql.*;
148public class Computer_server
149{ public static void main(String args[])
150 { ServerSocket server=null;Server_thread thread;
151 Socket you=null;
152 while(true)
153 { try{ server=new ServerSocket(4331);
154 }
155 catch(IOException e1)
156 { System.out.println("正在监听"); //ServerSocket对象不能重复创建。
157 }
158 try{ you=server.accept();
159 System.out.println("客户的地址:"+you.getInetAddress());
160 }
161 catch (IOException e)
162 { System.out.println("正在等待客户");
163 }
164 if(you!=null)
165 { new Server_thread(you).start(); //为每个客户启动一个专门的线程。
166 }
167 else
168 { continue;
169 }
170 }
171 }
172}
173class Server_thread extends Thread
174{ Socket socket;Connection Con=null;Statement Stmt=null;
175 DataOutputStream out=null;DataInputStream in=null;int n=0;
176 String s=null;
177 Server_thread(Socket t)
178 { socket=t;
179 try { in=new DataInputStream(socket.getInputStream());
180 out=new DataOutputStream(socket.getOutputStream());
181 }
182 catch (IOException e)
183 {}
184 }
185 public void run()
186 { while(true)
187 { double a[]=new double[3] ;int i=0;
188 try{ s=in.readUTF();堵塞状态,除非读取到信息。
189
190 StringTokenizer fenxi=new StringTokenizer(s," ,");
191 while(fenxi.hasMoreTokens())
192 { String temp=fenxi.nextToken();
193 try{ a[i]=Double.valueOf(temp).doubleValue();i++;
194 }
195 catch(NumberFormatException e)
196 { out.writeUTF("请输入数字字符");
197 }
198 }
199 double p=(a[0]+a[1]+a[2])/2.0;
200 out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
201 sleep(2);
202 }
203 catch(InterruptedException e){}
204 catch (IOException e)
205 { System.out.println("客户离开");
206 break;
207 }
208 }
209 }
210}
211
212//例子4
213import java.net.*;
214public class DomainName
215{ public static void main(String args[])
216 { try{ InetAddress address_1=InetAddress.getByName("www.sina.com.cn");
217 System.out.println(address_1.toString());
218 InetAddress address_2=InetAddress.getByName("166.111.222.3");
219 System.out.println(address_2.toString());
220 }
221 catch(UnknownHostException e)
222 { System.out.println("无法找到 www.sina.com.cn");
223 }
224 }
225}
226
227//例子5
228import java.net.*;
229public class DomainName
230{ public static void main(String args[])
231 { try{ InetAddress address=InetAddress.getByName("www.yahoo.com");
232 String domain_name=address.getHostName();//获取 address所含的域名。
233 String IP_name=address.getHostAddress(); //获取 address所含的IP地址。
234 System.out.println(domain_name);
235 System.out.println(IP_name);
236 }
237 catch(UnknownHostException e)
238 { System.out.println("无法找到 www.yahoo.com");
239 }
240 }
241}
242
243//例子6
244import java.net.*;
245public class DomainName
246{ public static void main(String args[])
247 { try{ InetAddress address=InetAddress.getLocalHost();
248 String domain_name=address.getHostName();//获取 address所含的域名。
249 String IP_name=address.getHostAddress();//获取 address所含的IP地址。
250 System.out.println(domain_name);
251 System.out.println(IP_name);
252 }
253 catch(UnknownHostException e){}
254 }
255}
256
257//例子7
258主机1:
259import java.net.*;import java.awt.*; import java.awt.event.*;
260class Shanghai_Frame extends Frame implements Runnable,ActionListener
261{ TextField out_message=new TextField("发送数据到北京:");
262 TextArea in_message=new TextArea();
263 Button b=new Button("发送数据包到北京");
264 Shanghai_Frame()
265 { super("我是上海");
266 setSize(200,200);setVisible(true);
267 b.addActionListener(this);
268 add(out_message,"South");add(in_message,"Center");add(b,"North");
269 Thread thread=new Thread(this);
270 thread.start();//线程负责接收数据包
271 }
272 //点击按扭发送数据包:
273 public void actionPerformed(ActionEvent event)
274 { byte buffer[]=out_message.getText().trim().getBytes();
275 try{ InetAddress address=InetAddress.getByName("localhost");
276 //数据包的目标端口是888(那么收方(北京)需在这个端口接收):
277 DatagramPacket data_pack=
278new DatagramPacket(buffer,buffer.length, address,888);
279 DatagramSocket mail_data=new DatagramSocket();
280 in_message.append("数据报目标主机地址:"+data_pack.getAddress()+"\n");
281 in_message.append("数据报目标端口是:"+data_pack.getPort()+"\n");
282 in_message.append("数据报长度:"+data_pack.getLength()+"\n");
283 mail_data.send(data_pack);
284 }
285 catch(Exception e){}
286 }
287 //接收数据包:
288 public void run()
289 { DatagramPacket pack=null;
290 DatagramSocket mail_data=null;
291 byte data[]=new byte[8192];
292 try{
293 pack=new DatagramPacket(data,data.length);
294 //使用端口666来接收数据包(因为北京发来的数据报的目标端口是666)。
295 mail_data=new DatagramSocket(666);
296 }
297 catch(Exception e){}
298 while(true)
299 { if(mail_data==null) break;
300 else
301 try{ mail_data.receive(pack);
302 int length=pack.getLength(); //获取收到的数据的实际长度。
303 InetAddress adress=pack.getAddress();//获取收到的数据包的始发地址。
304 int port=pack.getPort();//获取收到的数据包的始发端口。
305 String message=new String(pack.getData(),0,length);
306 in_message.append("收到数据长度:"+length+"\n");
307 in_message.append("收到数据来自:"+adress+"端口:"+port+"\n");
308 in_message.append("收到数据是:"+message+"\n");
309 }
310 catch(Exception e){}
311 }
312 }
313}
314public class Shanghai
315{ public static void main(String args[])
316 { Shanghai_Frame shanghai_win=new Shanghai_Frame();
317 shanghai_win.addWindowListener(new WindowAdapter()
318 { public void windowClosing(WindowEvent e)
319 {System.exit(0);
320 }
321 });
322 shanghai_win.pack();
323 }
324}
325
326主机2:
327import java.net.*;import java.awt.*; import java.awt.event.*;
328class Beijing_Frame extends Frame implements Runnable,ActionListener
329{ TextField out_message=new TextField("发送数据到上海:");
330 TextArea in_message=new TextArea();
331 Button b=new Button("发送数据包到上海");
332 Beijing_Frame()
333 { super("我是北京");
334 setSize(200,200);setVisible(true);
335 b.addActionListener(this);
336 add(out_message,"South");add(in_message,"Center");add(b,"North");
337 Thread thread=new Thread(this);
338 thread.start();//线程负责接收数据包
339 }
340//点击按扭发送数据包:
341 public void actionPerformed(ActionEvent event)
342 { byte buffer[]=out_message.getText().trim().getBytes();
343 try{ InetAddress address=InetAddress.getByName("localhost");
344 //数据包的目标端口是666(那么收方(上海)需在这个端口接收):
345 DatagramPacket data_pack=
346new DatagramPacket(buffer,buffer.length, address,666);
347 DatagramSocket mail_data=new DatagramSocket();
348 in_message.append("数据报目标主机地址:"+data_pack.getAddress()+"\n");
349 in_message.append("数据报目标端口是:"+data_pack.getPort()+"\n");
350 in_message.append("数据报长度:"+data_pack.getLength()+"\n");
351 mail_data.send(data_pack);
352 }
353 catch(Exception e){}
354 }
355 public void run()
356 { DatagramSocket mail_data=null;
357 byte data[]=new byte[8192];
358 DatagramPacket pack=null;
359 try{
360 pack=new DatagramPacket(data,data.length);
361 //使用端口888来接收数据包(因为上海发来的数据报的目标端口是888)。
362 mail_data=new DatagramSocket(888);
363 }
364 catch(Exception e){}
365 while(true)
366 { if(mail_data==null) break;
367 else
368 try{ mail_data.receive(pack);
369 int length=pack.getLength(); //获取收到的数据的实际长度。
370 InetAddress adress=pack.getAddress();//获取收到的数据包的始发地址。
371 int port=pack.getPort();//获取收到的数据包的始发端口。
372 String message=new String(pack.getData(),0,length);
373 in_message.append("收到数据长度:"+length+"\n");
374 in_message.append("收到数据来自:"+adress+"端口:"+port+"\n");
375 in_message.append("收到数据是:"+message+"\n");
376 }
377 catch(Exception e){}
378 }
379 }
380}
381public class Beijing
382{ public static void main(String args[])
383 { Beijing_Frame beijing_win=new Beijing_Frame();
384 beijing_win.addWindowListener(new WindowAdapter()
385 { public void windowClosing(WindowEvent e)
386 {System.exit(0);
387 }
388 });
389 beijing_win.pack();
390 }
391}
392
393//例子8
394BroadCast.java:
395import java.net.*;
396public class BroadCast extends Thread
397{ String s="天气预报,最高温度32度,最低温度25度";
398 int port=5858; //组播的端口.
399 InetAddress group=null; //组播组的地址.
400 MulticastSocket socket=null; //多点广播套接字.
401 BroadCast()
402 {try
403 {
404 group=InetAddress.getByName("239.255.8.0"); //设置广播组的地址为239.255.8.0。
405 socket=new MulticastSocket(port); //多点广播套接字将在port端口广播。
406 socket.setTimeToLive(1); //多点广播套接字发送数据报范围为本地网络。
407 socket.joinGroup(group); //加入广播组,加入group后,socket发送的数据报,
408 //可以被加入到group中的成员接收到。
409 }
410 catch(Exception e)
411 { System.out.println("Error: "+ e);
412 }
413 }
414 public void run()
415 { while(true)
416 { try
417 { DatagramPacket packet=null; //待广播的数据包。
418 byte data[]=s.getBytes();
419 packet=new DatagramPacket(data,data.length,group,port);
420 System.out.println(new String(data));
421 socket.send(packet); //广播数据包。
422 sleep(2000);
423 }
424 catch(Exception e)
425 { System.out.println("Error: "+ e);
426 }
427 }
428 }
429 public static void main(String args[])
430 {
431 new BroadCast().start();
432 }
433}
434
435Receive.java :
436
437import java.net.*;import java.awt.*;
438import java.awt.event.*;
439public class Receive extends Frame implements Runnable,ActionListener
440{ int port; //组播的端口.
441 InetAddress group=null; //组播组的地址.
442 MulticastSocket socket=null; //多点广播套接字.
443 Button 开始接收,停止接收;
444 TextArea 显示正在接收内容,显示已接收的内容;
445 Thread thread; //负责接收信息的线程.
446 boolean 停止=false;
447 public Receive()
448 { super("定时接收信息");
449 thread=new Thread(this);
450 开始接收=new Button("开始接收");
451 停止接收=new Button("停止接收");
452 停止接收.addActionListener(this);
453 开始接收.addActionListener(this);
454 显示正在接收内容=new TextArea(10,10);
455 显示正在接收内容.setForeground(Color.blue);
456 显示已接收的内容=new TextArea(10,10);
457 Panel north=new Panel();
458 north.add(开始接收);
459 north.add(停止接收);
460 add(north,BorderLayout.NORTH);
461 Panel center=new Panel();
462 center.setLayout(new GridLayout(1,2));
463 center.add(显示正在接收内容);
464 center.add(显示已接收的内容);
465 add(center,BorderLayout.CENTER);
466 validate();
467 port=5858; //设置组播组的监听端口。
468 try{
469 group=InetAddress.getByName("239.255.8.0"); /设置广播组的地址为239.255.8.0。
470 socket=new MulticastSocket(port); //多点广播套接字将在port端口广播。
471 socket.joinGroup(group); //加入广播组,加入group后,socket发送的数据报,
472 //可以被加入到group中的成员接收到。
473 }
474 catch(Exception e)
475 { }
476 setBounds(100,50,360,380);
477 setVisible(true);
478 addWindowListener(new WindowAdapter()
479 { public void windowClosing(WindowEvent e)
480 { System.exit(0);
481 }
482 });
483
484 }
485 public void actionPerformed(ActionEvent e)
486 { if(e.getSource()==开始接收)
487 { 开始接收.setBackground(Color.blue);
488 停止接收.setBackground(Color.gray);
489 if(!(thread.isAlive()))
490 { thread=new Thread(this);
491 }
492 try{ thread.start();
493 停止=false;
494 }
495 catch(Exception ee) {}
496 }
497 if(e.getSource()==停止接收)
498 { 开始接收.setBackground(Color.gray);
499 停止接收.setBackground(Color.blue);
500 thread.interrupt();
501 停止=true;
502 }
503 }
504 public void run()
505 { while(true)
506 {byte data[]=new byte[8192];
507 DatagramPacket packet=null;
508 packet=new DatagramPacket(data,data.length,group,port); //待接收的数据包。
509 try { socket.receive(packet);
510 String message=new String(packet.getData(),0,packet.getLength());
511 显示正在接收内容.setText("正在接收的内容:\n"+message);
512 显示已接收的内容.append(message+"\n");
513 }
514 catch(Exception e) {}
515 if(停止==true)
516 { break;
517 }
518 }
519 }
520
521 public static void main(String args[])
522 {
523 new Receive();
524 }
525}
526
2import java.applet.*;import java.awt.*;
3import java.awt.event.*;import java.net.*;
4public class Example21_1 extends Applet implements ActionListener
5{ Button button;
6 URL url;
7 TextField text;
8 public void init()
9 { text=new TextField(18);
10 button=new Button("确定");
11 add(new Label("输入网址:"));add(text); add(button);
12 button.addActionListener(this);
13 }
14 public void actionPerformed(ActionEvent e)
15 { if(e.getSource()==button)
16 { try { url=new URL(text.getText().trim());
17 getAppletContext().showDocument(url);
18 }
19 catch(MalformedURLException g)
20 { text.setText("不正确的URL:"+url);
21 }
22 }
23 }
24}
25
26//例子2
27(1)客户端程序:
28import java.io.*;
29import java.net.*;
30public class Client
31{ public static void main(String args[])
32 { String s=null;
33 Socket mysocket;
34 DataInputStream in=null;
35 DataOutputStream out=null;
36 try{
37 mysocket=new Socket("localhost",4331);
38 in=new DataInputStream(mysocket.getInputStream());
39 out=new DataOutputStream(mysocket.getOutputStream());
40 out.writeUTF("你好!");//通过 out向"线路"写入信息。
41 while(true)
42 {
43 s=in.readUTF();//通过使用in读取服务器放入"线路"里的信息。堵塞状态,
44 //除非读取到信息。
45 out.writeUTF(":"+Math.random());
46 System.out.println("客户收到:"+s);
47 Thread.sleep(500);
48 }
49 }
50 catch(IOException e)
51 { System.out.println("无法连接");
52 }
53 catch(InterruptedException e){}
54 }
55}
56(2)服务器端程序:
57import java.io.*;import java.net.*;
58public class Server
59{ public static void main(String args[])
60 { ServerSocket server=null;
61 Socket you=null;String s=null;
62 DataOutputStream out=null;DataInputStream in=null;
63 try{ server=new ServerSocket(4331);}
64 catch(IOException e1){System.out.println("ERRO:"+e1);}
65 try{ you=server.accept();
66 in=new DataInputStream(you.getInputStream());
67 out=new DataOutputStream(you.getOutputStream());
68 while(true)
69 {
70 s=in.readUTF();// 通过使用in读取客户放入"线路"里的信息。堵塞状态,
71 //除非读取到信息。
72
73 out.writeUTF("你好:我是服务器");//通过 out向"线路"写入信息.
74 out.writeUTF("你说的数是:"+s);
75 System.out.println("服务器收到:"+s);
76 Thread.sleep(500);
77 }
78 }
79 catch(IOException e)
80 { System.out.println(""+e);
81 }
82 catch(InterruptedException e){}
83 }
84}
85
86//例子3
87 (1) 客户端
88import java.net.*;import java.io.*;
89import java.awt.*;import java.awt.event.*;
90import java.applet.*;
91public class Computer_client extends Applet implements Runnable,ActionListener
92{ Button 计算;TextField 输入三边长度文本框,计算结果文本框;
93 Socket socket=null;
94 DataInputStream in=null; DataOutputStream out=null;
95 Thread thread;
96 public void init()
97 { setLayout(new GridLayout(2,2));
98 Panel p1=new Panel(),p2=new Panel();
99 计算=new Button(" 计算");
100 输入三边长度文本框=new TextField(12);计算结果文本框=new TextField(12);
101 p1.add(new Label("输入三角形三边的长度,用逗号或空格分隔:"));
102 p1.add( 输入三边长度文本框);
103 p2.add(new Label("计算结果:"));p2.add(计算结果文本框);p2.add(计算);
104 计算.addActionListener(this);
105 add(p1);add(p2);
106 }
107 public void start()
108 { try
109 { //和小程序所驻留的服务器建立套接字连接:
110 socket = new Socket(this.getCodeBase().getHost(), 4331);
111 in =new DataInputStream(socket.getInputStream());
112 out = new DataOutputStream(socket.getOutputStream());
113 }
114 catch (IOException e){}
115 if(thread == null)
116 { thread = new Thread(this);
117 thread.start();
118 }
119 }
120 public void run()
121 { String s=null;
122 while(true)
123 { try{ s=in.readUTF();//堵塞状态,除非读取到信息。
124
125 计算结果文本框.setText(s);
126 }
127 catch(IOException e)
128{ 计算结果文本框.setText("与服务器已断开");
129 break;
130}
131 }
132 }
133 public void actionPerformed(ActionEvent e)
134 { if(e.getSource()==计算)
135 { String s=输入三边长度文本框.getText();
136 if(s!=null)
137 { try { out.writeUTF(s);
138 }
139 catch(IOException e1){}
140 }
141 }
142 }
143}
144
145 (2) 服务器端
146import java.io.*;import java.net.*;
147import java.util.*;import java.sql.*;
148public class Computer_server
149{ public static void main(String args[])
150 { ServerSocket server=null;Server_thread thread;
151 Socket you=null;
152 while(true)
153 { try{ server=new ServerSocket(4331);
154 }
155 catch(IOException e1)
156 { System.out.println("正在监听"); //ServerSocket对象不能重复创建。
157 }
158 try{ you=server.accept();
159 System.out.println("客户的地址:"+you.getInetAddress());
160 }
161 catch (IOException e)
162 { System.out.println("正在等待客户");
163 }
164 if(you!=null)
165 { new Server_thread(you).start(); //为每个客户启动一个专门的线程。
166 }
167 else
168 { continue;
169 }
170 }
171 }
172}
173class Server_thread extends Thread
174{ Socket socket;Connection Con=null;Statement Stmt=null;
175 DataOutputStream out=null;DataInputStream in=null;int n=0;
176 String s=null;
177 Server_thread(Socket t)
178 { socket=t;
179 try { in=new DataInputStream(socket.getInputStream());
180 out=new DataOutputStream(socket.getOutputStream());
181 }
182 catch (IOException e)
183 {}
184 }
185 public void run()
186 { while(true)
187 { double a[]=new double[3] ;int i=0;
188 try{ s=in.readUTF();堵塞状态,除非读取到信息。
189
190 StringTokenizer fenxi=new StringTokenizer(s," ,");
191 while(fenxi.hasMoreTokens())
192 { String temp=fenxi.nextToken();
193 try{ a[i]=Double.valueOf(temp).doubleValue();i++;
194 }
195 catch(NumberFormatException e)
196 { out.writeUTF("请输入数字字符");
197 }
198 }
199 double p=(a[0]+a[1]+a[2])/2.0;
200 out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
201 sleep(2);
202 }
203 catch(InterruptedException e){}
204 catch (IOException e)
205 { System.out.println("客户离开");
206 break;
207 }
208 }
209 }
210}
211
212//例子4
213import java.net.*;
214public class DomainName
215{ public static void main(String args[])
216 { try{ InetAddress address_1=InetAddress.getByName("www.sina.com.cn");
217 System.out.println(address_1.toString());
218 InetAddress address_2=InetAddress.getByName("166.111.222.3");
219 System.out.println(address_2.toString());
220 }
221 catch(UnknownHostException e)
222 { System.out.println("无法找到 www.sina.com.cn");
223 }
224 }
225}
226
227//例子5
228import java.net.*;
229public class DomainName
230{ public static void main(String args[])
231 { try{ InetAddress address=InetAddress.getByName("www.yahoo.com");
232 String domain_name=address.getHostName();//获取 address所含的域名。
233 String IP_name=address.getHostAddress(); //获取 address所含的IP地址。
234 System.out.println(domain_name);
235 System.out.println(IP_name);
236 }
237 catch(UnknownHostException e)
238 { System.out.println("无法找到 www.yahoo.com");
239 }
240 }
241}
242
243//例子6
244import java.net.*;
245public class DomainName
246{ public static void main(String args[])
247 { try{ InetAddress address=InetAddress.getLocalHost();
248 String domain_name=address.getHostName();//获取 address所含的域名。
249 String IP_name=address.getHostAddress();//获取 address所含的IP地址。
250 System.out.println(domain_name);
251 System.out.println(IP_name);
252 }
253 catch(UnknownHostException e){}
254 }
255}
256
257//例子7
258主机1:
259import java.net.*;import java.awt.*; import java.awt.event.*;
260class Shanghai_Frame extends Frame implements Runnable,ActionListener
261{ TextField out_message=new TextField("发送数据到北京:");
262 TextArea in_message=new TextArea();
263 Button b=new Button("发送数据包到北京");
264 Shanghai_Frame()
265 { super("我是上海");
266 setSize(200,200);setVisible(true);
267 b.addActionListener(this);
268 add(out_message,"South");add(in_message,"Center");add(b,"North");
269 Thread thread=new Thread(this);
270 thread.start();//线程负责接收数据包
271 }
272 //点击按扭发送数据包:
273 public void actionPerformed(ActionEvent event)
274 { byte buffer[]=out_message.getText().trim().getBytes();
275 try{ InetAddress address=InetAddress.getByName("localhost");
276 //数据包的目标端口是888(那么收方(北京)需在这个端口接收):
277 DatagramPacket data_pack=
278new DatagramPacket(buffer,buffer.length, address,888);
279 DatagramSocket mail_data=new DatagramSocket();
280 in_message.append("数据报目标主机地址:"+data_pack.getAddress()+"\n");
281 in_message.append("数据报目标端口是:"+data_pack.getPort()+"\n");
282 in_message.append("数据报长度:"+data_pack.getLength()+"\n");
283 mail_data.send(data_pack);
284 }
285 catch(Exception e){}
286 }
287 //接收数据包:
288 public void run()
289 { DatagramPacket pack=null;
290 DatagramSocket mail_data=null;
291 byte data[]=new byte[8192];
292 try{
293 pack=new DatagramPacket(data,data.length);
294 //使用端口666来接收数据包(因为北京发来的数据报的目标端口是666)。
295 mail_data=new DatagramSocket(666);
296 }
297 catch(Exception e){}
298 while(true)
299 { if(mail_data==null) break;
300 else
301 try{ mail_data.receive(pack);
302 int length=pack.getLength(); //获取收到的数据的实际长度。
303 InetAddress adress=pack.getAddress();//获取收到的数据包的始发地址。
304 int port=pack.getPort();//获取收到的数据包的始发端口。
305 String message=new String(pack.getData(),0,length);
306 in_message.append("收到数据长度:"+length+"\n");
307 in_message.append("收到数据来自:"+adress+"端口:"+port+"\n");
308 in_message.append("收到数据是:"+message+"\n");
309 }
310 catch(Exception e){}
311 }
312 }
313}
314public class Shanghai
315{ public static void main(String args[])
316 { Shanghai_Frame shanghai_win=new Shanghai_Frame();
317 shanghai_win.addWindowListener(new WindowAdapter()
318 { public void windowClosing(WindowEvent e)
319 {System.exit(0);
320 }
321 });
322 shanghai_win.pack();
323 }
324}
325
326主机2:
327import java.net.*;import java.awt.*; import java.awt.event.*;
328class Beijing_Frame extends Frame implements Runnable,ActionListener
329{ TextField out_message=new TextField("发送数据到上海:");
330 TextArea in_message=new TextArea();
331 Button b=new Button("发送数据包到上海");
332 Beijing_Frame()
333 { super("我是北京");
334 setSize(200,200);setVisible(true);
335 b.addActionListener(this);
336 add(out_message,"South");add(in_message,"Center");add(b,"North");
337 Thread thread=new Thread(this);
338 thread.start();//线程负责接收数据包
339 }
340//点击按扭发送数据包:
341 public void actionPerformed(ActionEvent event)
342 { byte buffer[]=out_message.getText().trim().getBytes();
343 try{ InetAddress address=InetAddress.getByName("localhost");
344 //数据包的目标端口是666(那么收方(上海)需在这个端口接收):
345 DatagramPacket data_pack=
346new DatagramPacket(buffer,buffer.length, address,666);
347 DatagramSocket mail_data=new DatagramSocket();
348 in_message.append("数据报目标主机地址:"+data_pack.getAddress()+"\n");
349 in_message.append("数据报目标端口是:"+data_pack.getPort()+"\n");
350 in_message.append("数据报长度:"+data_pack.getLength()+"\n");
351 mail_data.send(data_pack);
352 }
353 catch(Exception e){}
354 }
355 public void run()
356 { DatagramSocket mail_data=null;
357 byte data[]=new byte[8192];
358 DatagramPacket pack=null;
359 try{
360 pack=new DatagramPacket(data,data.length);
361 //使用端口888来接收数据包(因为上海发来的数据报的目标端口是888)。
362 mail_data=new DatagramSocket(888);
363 }
364 catch(Exception e){}
365 while(true)
366 { if(mail_data==null) break;
367 else
368 try{ mail_data.receive(pack);
369 int length=pack.getLength(); //获取收到的数据的实际长度。
370 InetAddress adress=pack.getAddress();//获取收到的数据包的始发地址。
371 int port=pack.getPort();//获取收到的数据包的始发端口。
372 String message=new String(pack.getData(),0,length);
373 in_message.append("收到数据长度:"+length+"\n");
374 in_message.append("收到数据来自:"+adress+"端口:"+port+"\n");
375 in_message.append("收到数据是:"+message+"\n");
376 }
377 catch(Exception e){}
378 }
379 }
380}
381public class Beijing
382{ public static void main(String args[])
383 { Beijing_Frame beijing_win=new Beijing_Frame();
384 beijing_win.addWindowListener(new WindowAdapter()
385 { public void windowClosing(WindowEvent e)
386 {System.exit(0);
387 }
388 });
389 beijing_win.pack();
390 }
391}
392
393//例子8
394BroadCast.java:
395import java.net.*;
396public class BroadCast extends Thread
397{ String s="天气预报,最高温度32度,最低温度25度";
398 int port=5858; //组播的端口.
399 InetAddress group=null; //组播组的地址.
400 MulticastSocket socket=null; //多点广播套接字.
401 BroadCast()
402 {try
403 {
404 group=InetAddress.getByName("239.255.8.0"); //设置广播组的地址为239.255.8.0。
405 socket=new MulticastSocket(port); //多点广播套接字将在port端口广播。
406 socket.setTimeToLive(1); //多点广播套接字发送数据报范围为本地网络。
407 socket.joinGroup(group); //加入广播组,加入group后,socket发送的数据报,
408 //可以被加入到group中的成员接收到。
409 }
410 catch(Exception e)
411 { System.out.println("Error: "+ e);
412 }
413 }
414 public void run()
415 { while(true)
416 { try
417 { DatagramPacket packet=null; //待广播的数据包。
418 byte data[]=s.getBytes();
419 packet=new DatagramPacket(data,data.length,group,port);
420 System.out.println(new String(data));
421 socket.send(packet); //广播数据包。
422 sleep(2000);
423 }
424 catch(Exception e)
425 { System.out.println("Error: "+ e);
426 }
427 }
428 }
429 public static void main(String args[])
430 {
431 new BroadCast().start();
432 }
433}
434
435Receive.java :
436
437import java.net.*;import java.awt.*;
438import java.awt.event.*;
439public class Receive extends Frame implements Runnable,ActionListener
440{ int port; //组播的端口.
441 InetAddress group=null; //组播组的地址.
442 MulticastSocket socket=null; //多点广播套接字.
443 Button 开始接收,停止接收;
444 TextArea 显示正在接收内容,显示已接收的内容;
445 Thread thread; //负责接收信息的线程.
446 boolean 停止=false;
447 public Receive()
448 { super("定时接收信息");
449 thread=new Thread(this);
450 开始接收=new Button("开始接收");
451 停止接收=new Button("停止接收");
452 停止接收.addActionListener(this);
453 开始接收.addActionListener(this);
454 显示正在接收内容=new TextArea(10,10);
455 显示正在接收内容.setForeground(Color.blue);
456 显示已接收的内容=new TextArea(10,10);
457 Panel north=new Panel();
458 north.add(开始接收);
459 north.add(停止接收);
460 add(north,BorderLayout.NORTH);
461 Panel center=new Panel();
462 center.setLayout(new GridLayout(1,2));
463 center.add(显示正在接收内容);
464 center.add(显示已接收的内容);
465 add(center,BorderLayout.CENTER);
466 validate();
467 port=5858; //设置组播组的监听端口。
468 try{
469 group=InetAddress.getByName("239.255.8.0"); /设置广播组的地址为239.255.8.0。
470 socket=new MulticastSocket(port); //多点广播套接字将在port端口广播。
471 socket.joinGroup(group); //加入广播组,加入group后,socket发送的数据报,
472 //可以被加入到group中的成员接收到。
473 }
474 catch(Exception e)
475 { }
476 setBounds(100,50,360,380);
477 setVisible(true);
478 addWindowListener(new WindowAdapter()
479 { public void windowClosing(WindowEvent e)
480 { System.exit(0);
481 }
482 });
483
484 }
485 public void actionPerformed(ActionEvent e)
486 { if(e.getSource()==开始接收)
487 { 开始接收.setBackground(Color.blue);
488 停止接收.setBackground(Color.gray);
489 if(!(thread.isAlive()))
490 { thread=new Thread(this);
491 }
492 try{ thread.start();
493 停止=false;
494 }
495 catch(Exception ee) {}
496 }
497 if(e.getSource()==停止接收)
498 { 开始接收.setBackground(Color.gray);
499 停止接收.setBackground(Color.blue);
500 thread.interrupt();
501 停止=true;
502 }
503 }
504 public void run()
505 { while(true)
506 {byte data[]=new byte[8192];
507 DatagramPacket packet=null;
508 packet=new DatagramPacket(data,data.length,group,port); //待接收的数据包。
509 try { socket.receive(packet);
510 String message=new String(packet.getData(),0,packet.getLength());
511 显示正在接收内容.setText("正在接收的内容:\n"+message);
512 显示已接收的内容.append(message+"\n");
513 }
514 catch(Exception e) {}
515 if(停止==true)
516 { break;
517 }
518 }
519 }
520
521 public static void main(String args[])
522 {
523 new Receive();
524 }
525}
526