UDP

import java.net.*;
import java.io.*;
class  UdpSend2
{
	public static void main(String[] args)throws Exception 
	{

		//1,建立udp的socket服务。
		DatagramSocket ds = new DatagramSocket();

		//2,将数据封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port) 
		
		BufferedReader bufr = 
			new BufferedReader(new InputStreamReader(System.in));

		String line = null;
		while((line=bufr.readLine())!=null)
		{
			byte[] bys = line.getBytes();

			InetAddress ip = InetAddress.getByName("192.168.1.255");

			DatagramPacket dp = new DatagramPacket(bys,bys.length,ip,10000);

			//3,通过socket服务的send方法。将数据包仍出去。
			ds.send(dp);
		}

		//4,关闭资源。
		ds.close();

	}
}


class  UdpReceive2
{
	public static void main(String[] args) throws Exception
	{
		//1.建立socket服务,监听一个端口.
		DatagramSocket ds = new DatagramSocket(10000);

		//2,通过socket服务的receive()方法接收数据。
			//2.1建立一个数据包,用于存放数据,这样可以通过数据包的方法方便获取不同的数据信息。
		while(true)
		{
			byte[] buf = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buf,buf.length);

			ds.receive(dp);

			String ip = dp.getAddress().getHostAddress();

			String data = new String(dp.getData(),0,dp.getLength());

			int port = dp.getPort();

			System.out.println(ip+":"+port+"...."+data);
		}
		//ds.close();

	}
}

 

你可能感兴趣的:(UDP)