1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
入口: package
chat;
import java.net.DatagramSocket;
import java.net.SocketException;
public class chat {
/**
* @param args
* @throws SocketException
*/
public
static void main(String[] args) throws
SocketException {
// TODO Auto-generated method stub
DatagramSocket sd = new
DatagramSocket();
DatagramSocket re = new
DatagramSocket( 9000 );
send s = new
send(sd);
receive r = new
receive(re);
new
Thread(s).start();
new
Thread(r).start();
}
} <br><br> <br> 发送端: package
chat;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.net.DatagramPacket;
import
java.net.DatagramSocket;
import
java.net.InetAddress;
import
java.net.SocketException;
import
java.net.UnknownHostException;
public
class send implements
Runnable {
public
DatagramSocket ds;
public
send(DatagramSocket ds) throws
SocketException
{
this .ds = ds;
}
@Override
public
void run() {
// TODO Auto-generated method stub
try
{
InetAddress ip = InetAddress.getByName( "192.168.1.255" );
String line = null ;
//第三步:创建UDP数据包
System.out.println( "开始聊天了:" );
BufferedReader in = new
BufferedReader( new
InputStreamReader(System.in));
while ((line=in.readLine())!= null )
{
byte [] buf = line.getBytes();
DatagramPacket dp = new
DatagramPacket(buf, buf.length, ip, 9000 );
ds.send(dp);
if ( "over" .equals(line)) break ;
}
ds.close();
} catch
(UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch
(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} 接收端: package
chat;
import
java.io.IOException;
import
java.net.DatagramPacket;
import
java.net.DatagramSocket;
public
class receive implements
Runnable {
public
DatagramSocket ds;
public
receive(DatagramSocket ds)
{
this .ds = ds;
}
@Override
public
void run() {
// TODO Auto-generated method stub
try
{
byte [] buf = new
byte [ 1024 ];
while ( true )
{
DatagramPacket dp = new
DatagramPacket(buf,buf.length);
ds.receive(dp); //阻塞式
//第三步:解析接收到的udp包
String host = dp.getAddress().getHostName();
int
port = dp.getPort();
String data = new
String(dp.getData(), 0 ,dp.getLength());
System.out.println( "聊天内容是:" );
System.out.println(host+ ":" +data);
System.out.println( " " );
}
} catch
(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |