UDP socket编程

服务器端

public class UDPServer {

	public static void main(String[]args) throws Exception{
		
		byte[] buf = new byte[100];
		
		DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
		
		DatagramSocket datagramSocket = new DatagramSocket(9995);
		
		while(true){
			datagramSocket.receive(datagramPacket);
			System.out.println("data  is :" + new String(datagramPacket.getData()));
		}
	}
}

 

客户端

public class UDPClient {

	public static void main(String[] args) throws Exception {
		byte[] buf = new String("UDP TEST data from client").getBytes(); ;
		DatagramPacket datagramPacket = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),9995);
		DatagramSocket datagramSocket = new DatagramSocket();
		datagramSocket.send(datagramPacket);
	}
}

 

posted @ 2012-01-05 21:35  胖鹅  阅读(171)  评论(0编辑  收藏  举报