在Java中使用UDP完成消息发送。主要使用DatagramSocket和DatagramPacket对象,示例如下:
服务器端监听:
/**
* @author ZYWANG
* @date 2010-3-9
*/
public class UDPServer {
/**
* @param args
* @author ZYWANG
* @date 2010-3-9
*/
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(10000);
byte[] buffer = new byte[65508];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
while(true){
socket.receive(packet);
String s = new String(packet.getData(),0,packet.getLength());
System.out.println(s);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
/**
* @author ZYWANG
* @date 2010-3-9
*/
public class UDPClient {
/**
* @param args
* @author ZYWANG
* @date 2010-3-9
*/
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();
String s = "测试文字ABC";
byte[] buffer = s.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,InetAddress.getByName("127.0.0.1"),10000);
socket.send(packet);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}