www.pudn.com > java_udp.rar > DatagramServer.java, change:2008-10-11,size:1325b


package com.zx.udp; 
 
import java.io.IOException; 
import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.SocketException; 
import java.net.UnknownHostException; 
 
public class DatagramServer { 
	 
	private static int PORT = 8122; 
 
	public static void main(String[] args) { 
		try { 
			System.out.println("Datagram Server."); 
			byte[] buf = new byte[1000]; 
			// 开始监视12345端口 
			DatagramSocket ds = new DatagramSocket(PORT); 
			// 创建接收数据报的实例 
			DatagramPacket dp = new DatagramPacket(buf, buf.length); 
			 
			int i = 0; 
			while (true) { 
				// 阻塞,直到收到数据报后将数据装入dp中 
				ds.receive(dp); 
				System.out.println("ip: " + dp.getAddress().getHostAddress()); 
				System.out.println("port: " + dp.getPort()); 
				 
				String info = new String(dp.getData(), 0, dp.getLength()); 
				System.out.println("-------------"); 
				System.out.println(info.trim()); 
				 
				String str = "子轩"; 
				dp.setData(str.getBytes()); 
				//dp.setLength(str.getBytes().length); 
				ds.send(dp); 
				 
				i++; 
			} 
		} catch (SocketException e1) { 
			System.out.println("SocketException"); 
		} catch (UnknownHostException e11) { 
			System.out.println("UnknownHostException"); 
		} catch (IOException e) { 
			System.out.println("IOException"); 
		} 
	} 
 
}