1、Java實現方式
1)server端
/**
* UDPserver端
* */
public class UdpServer {
// 定義一些常量
private final intMAX_LENGTH = 1024; // 最大接收字節長度
private final intPORT_NUM = 5066; // port號
// 用以存放接收數據的字節數組
private byte[] receMsgs = new byte[MAX_LENGTH];
// 數據報套接字
private DatagramSocket datagramSocket;
// 用以接收數據報
private DatagramPacket datagramPacket;
public UdpServer(){
try {
/******* 接收數據流程**/
// 創建一個數據報套接字,並將其綁定到指定port上
datagramSocket = new DatagramSocket(PORT_NUM);
// DatagramPacket(byte buf[], int length),建立一個字節數組來接收UDP包
datagramPacket = new DatagramPacket(receMsgs, receMsgs.length);
// receive()來等待接收UDP數據報
datagramSocket.receive(datagramPacket);
/****** 解析數據報****/
String receStr = new String(datagramPacket.getData(), 0 , datagramPacket.getLength());
System.out.println("Server Rece:" + receStr);
System.out.println("Server Port:" + datagramPacket.getPort());
/***** 返回ACK消息數據報*/
// 組裝數據報
byte[] buf = "I receive the message".getBytes();
DatagramPacket sendPacket = new DatagramPacket(buf, buf.length, datagramPacket.getAddress(), datagramPacket.getPort());
// 發送消息
datagramSocket.send(sendPacket);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉socket
if (datagramSocket != null) {
datagramSocket.close();
}
}
}
}
2)client
/***
* UDPclientClient端
***/
public class UdpClient {
private String sendStr = "SendString";
private String netAddress = "127.0.0.1";
private final intPORT_NUM = 5066;
private DatagramSocket datagramSocket;
private DatagramPacket datagramPacket;
public UdpClient(){
try {
/*** 發送數據***/
// 初始化datagramSocket,注意與前面Server端實現的差別
datagramSocket = new DatagramSocket();
// 使用DatagramPacket(byte buf[], int length, InetAddress address, int port)函數組裝發送UDP數據報
byte[] buf = sendStr.getBytes();
InetAddress address = InetAddress.getByName(netAddress);
datagramPacket = new DatagramPacket(buf, buf.length, address, PORT_NUM);
// 發送數據
datagramSocket.send(datagramPacket);
/*** 接收數據***/
byte[] receBuf = new byte[1024];
DatagramPacket recePacket = new DatagramPacket(receBuf, receBuf.length);
datagramSocket.receive(recePacket);
String receStr = new String(recePacket.getData(), 0 , recePacket.getLength());
System.out.println("Client Rece Ack:" + receStr);
System.out.println(recePacket.getPort());
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉socket
if(datagramSocket != null){
datagramSocket.close();
}
}
}
}
