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


package com.zx.udp; 
 
import java.io.IOException; 
import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.InetAddress; 
import java.net.NetworkInterface; 
import java.net.SocketException; 
import java.net.UnknownHostException; 
import java.util.Enumeration; 
 
public class DatagramClient { 
 
	private static int PORT = 8122; // listen..... 
	private static int SENDPORT = 9999; // listen.... 
 
	public static void main(String[] args) { 
		try { 
			System.out.println("UDP CLient Start!"); 
			// {发送数据的客户端} 
			byte[] ip = { (byte) 192, (byte) 168, (byte) 1, (byte) 131 }; 
			NetworkInterface tmp_ni = null; 
			InetAddress tmp_ia = null; 
			Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces(); 
			String info = ""; 
 
			while (ni.hasMoreElements()) { 
				tmp_ni = ni.nextElement(); 
 
				String dispName = new String(tmp_ni.getDisplayName().getBytes(), "GB2312"); 
 
				info += "Interface(" + tmp_ni.getName() + "):" + dispName + "\n"; 
 
				Enumeration<InetAddress> ia = tmp_ni.getInetAddresses(); 
 
				while (ia.hasMoreElements()) { 
					tmp_ia = ia.nextElement(); 
					info += "\t ip:" + tmp_ia.getHostAddress() + "\n"; 
				} 
			} 
			 
			InetAddress target = InetAddress.getByAddress(ip); 
			System.out.println("Sent to :" + target.getHostAddress() + ":" + PORT); 
			// 得到目标机器的地址实例 
			DatagramSocket ds = new DatagramSocket(SENDPORT); 
			// 从9999端口发送数据报 
			//InetAddress local = InetAddress.getLocalHost(); 
			// 要发送的数据 
			String hello = info; 
			 
			// 将数据转换成Byte类型 
			byte[] buf = hello.getBytes(); 
 
			// 将BUF缓冲区中的数据打包 
			DatagramPacket dp = new DatagramPacket(buf, buf.length, target, PORT); 
			// 发送数据 
			while (true) { 
				dp.setData(info.getBytes()); 
				//dp.setLength(info.getBytes().length); 
				ds.send(dp); 
				System.out.println("send: "+info); 
				 
				ds.receive(dp); 
				String s = new String(dp.getData(), 0, dp.getLength()); 
				System.out.println("-------------"); 
				System.out.println("receive: "+s.trim()); 
				Thread.sleep(10000); 
			} 
			 
			// 关闭连接 
			//ds.close(); 
		} catch (SocketException e1) { 
			System.out.println("SocketException"); 
		} catch (UnknownHostException e11) { 
			System.out.println("UnknownHostException"); 
		} catch (IOException e) { 
			System.out.println("IOException"); 
		} catch (InterruptedException e1111) { 
			System.out.println("InterruptedException"); 
		} 
	} 
 
}