-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUDPClientA.java
More file actions
58 lines (53 loc) · 2.18 KB
/
UDPClientA.java
File metadata and controls
58 lines (53 loc) · 2.18 KB
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
package org.renlr.test;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
public class UDPClientA {
public static void main(String[] args) {
try {
// 向server发起请求
SocketAddress target = new InetSocketAddress("10.1.11.137", 2008);
DatagramSocket client = new DatagramSocket();
String message = "I am UPDClinetA 192.168.85.132";
byte[] sendbuf = message.getBytes();
DatagramPacket pack = new DatagramPacket(sendbuf, sendbuf.length, target);
client.send(pack);
// 接收请求的回复,可能不是server回复的,有可能来自UPDClientB的请求内
receive(client);
} catch (Exception e) {
e.printStackTrace();
}
}
//接收请求内容
private static void receive(DatagramSocket client) {
try {
for (;;) {
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
client.receive(packet);
String receiveMessage = new String(packet.getData(), 0, packet.getLength());
System.out.println(receiveMessage);
int port = packet.getPort();
InetAddress address = packet.getAddress();
String reportMessage = "tks";
//获取接收到请问内容后并取到地址与端口,然后用获取到地址与端口回复内容
sendMessaage(reportMessage, port, address, client);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//回复内容
private static void sendMessaage(String reportMessage, int port, InetAddress address, DatagramSocket client) {
try {
byte[] sendBuf = reportMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, address, port);
client.send(sendPacket);
System.out.println("消息发送成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}