博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java Socket(四)使用UDP传输数据
阅读量:6034 次
发布时间:2019-06-20

本文共 1941 字,大约阅读时间需要 6 分钟。

hot3.png

参考资料:

package socket;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UDPSocketClient {	public static void main(String[] args) throws IOException 	{		//1.定义服务器的地址、端口、数据		InetAddress address= InetAddress.getByName("localhost");		int port = 8800;		byte[] data = "Hello".getBytes();				//2创建数据报		DatagramPacket packet = new DatagramPacket(data, data.length, address, port);	    		//3创建DatagramSocket		DatagramSocket socket = new DatagramSocket();		//4发送数据	        socket.send(packet);		System.out.println("Sended");								/*		 * 接收服务器端相应的信息		 */		//1.创建数据报		byte[] respdata = new byte[1024];		DatagramPacket resppacket = new DatagramPacket(respdata, respdata.length);		//2.接收服务器响应的数据		socket.receive(resppacket);		//3.转为字符串		String reply = new String(respdata, 0, resppacket.getLength());		System.out.println("received:" + reply);								//关闭资源		socket.close();	}}package socket;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UDPSocketServer {	public static void main(String[] args) throws IOException 	{		// 1创建服务器端,并指定端口		DatagramSocket socket = new DatagramSocket(8800);		// 2创建数据报		byte[] data = new byte[1024];		DatagramPacket packet = new DatagramPacket(data, data.length);		// 3 接收客户端发送的数据		System.out.println("wait for client...");		socket.receive(packet);// 此方法在接收到数据之前会一直阻塞		String info = new String(data, 0, packet.getLength());		System.out.println("Server side get:" + info);				/*		 * 向客户端相应		 */		//客户端地址、端口、数据		InetAddress address = packet.getAddress();	        int port = packet.getPort();	        byte[] respdata = "Hello,too!".getBytes();	        //创建数据报,并绑定相应信息	        DatagramPacket resppacket= new DatagramPacket(respdata, respdata.length,	    		address, port);	        socket.send(resppacket);	    	}}

转载于:https://my.oschina.net/liuyuanyuangogo/blog/812113

你可能感兴趣的文章