Java UDP 数据报

服务端,创建一个DatagramSocket对象,侦听在某个端口,创建一个DatagramPacket对象接受数据。收到客户端发来的信息后,有原封不动转发到客户端。

public class DatagramServerTest {

	public static void main(String[] args) throws IOException {

		byte[] buf = new byte[1024];

		DatagramPacket packet = new DatagramPacket(buf, 1024);

		DatagramSocket server = new DatagramSocket(9000); //侦听本机9000端口UDP数据包

		

		server.receive(packet);

		

		String str = new String(buf,0,packet.getLength());

		System.out.println("server get msg -> "+packet.getAddress().getHostName()+":"+str);

		

		server.send(new DatagramPacket(buf,packet.getLength(),packet.getAddress(),packet.getPort()));

		

		server.close();

	}

}

 客户端,创建一个DatagramSocket对象和一个DatagramPacket对象(包含目的主机的端口号9000和IP地址),调用send方法,发送数据.然后调用receive接受服务器的回传@

  

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

import java.net.UnknownHostException;



public class DatagramClientTest {

	public static void main(String[] args) throws IOException {

		//创建UDP的Socket

        InetAddress serverAddr = InetAddress.getByName("192.168.0.101");	//目的主机IP地址

		DatagramSocket client = new DatagramSocket();//本地端口随机,直接创建DatagramSocket

		

		String str = "hello world, from " + InetAddress.getLocalHost().getHostName();

		DatagramPacket packet = new DatagramPacket(str.getBytes(), str.length(), serverAddr, 9000);	//目的主机端口号9000

		

		client.send(packet);

		byte[] buf = new byte[1024];

		DatagramPacket pkt = new DatagramPacket(buf,1024);

		client.receive(pkt);

		String str1 = new String(buf,0,pkt.getLength());

		System.out.println("client get -> "+packet.getAddress().getHostName()+":"+str1);

		client.close();

	}

}

 

你可能感兴趣的:(java)