UDP代码示例 UDPServer UDPClient
- 2015-09-01 22:42:00
- admin
- 原创 1847
一、UDP使用讲解
1、UDP特性:不可靠通信,可能丢包,无序到达,单个包最大64K;
2、void setSoTimeout(int timeout),设置读取数据的超时时间;
二、UDPServer
代码下载:UDPServer.java
public class UDPServer {
private static final int SERVER_PORT = 9101;
private static final int CLIENT_PORT = 9201;
private DatagramSocket dataSocket;
private DatagramPacket sendPack;
private DatagramPacket recvPack;
private byte sendByte[];
private byte recvByte[];
private String recvStr;
public UDPServer() {
init();
}
private DatagramPacket getSendPack(String str, InetAddress addr, int port) {
sendByte = str.getBytes();
try {
return new DatagramPacket(sendByte, sendByte.length, addr, port);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void init() {
try {
dataSocket = new DatagramSocket(SERVER_PORT);
recvByte = new byte[1024];
recvPack = new DatagramPacket(recvByte, recvByte.length);
int cnt = 0;
int len = 0;
while (len == 0) {
++cnt;
System.out.print("recv cnt is " + cnt + ": ");
dataSocket.receive(recvPack);
len = recvPack.getLength();
if (len > 0) {
recvStr = new String(recvByte, 0, recvPack.getLength());
System.out.println(recvStr);
len = 0;
sendPack = getSendPack("服务端data",
recvPack.getAddress(), recvPack.getPort());
dataSocket.send(sendPack);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
new UDPServer();
}
}
三、UDPClient
代码下载:UDPClient.java
public class UDPClient {
private static final int SERVER_PORT = 9101;
private static final int CLIENT_PORT = 9201;
private DatagramSocket dataSocket;
private DatagramPacket sendPack;
private DatagramPacket recvPack;
private byte sendByte[];
private byte recvByte[];
private String recvStr;
public UDPClient() {
init();
}
private DatagramPacket getSendPack(String str) {
sendByte = str.getBytes();
try {
return new DatagramPacket(sendByte, sendByte.length,
InetAddress.getByName("localhost"), SERVER_PORT);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String toString(DatagramPacket dp) {
return new String(dp.getData(), 0, dp.getLength());
}
private void init() {
try {
dataSocket = new DatagramSocket(CLIENT_PORT);
recvByte = new byte[1024];
recvPack = new DatagramPacket(recvByte, recvByte.length);
sendPack = getSendPack("客户端data");
dataSocket.send(sendPack);
dataSocket.receive(recvPack);
String data = toString(recvPack)
+ ",from address:" + recvPack.getAddress()
+ ",port:" + recvPack.getPort();
System.out.println("UDPClient: " + data);
} catch (SocketException se) {
se.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
public static void main(String args[]) {
new UDPClient();
}
}