Java Socket(四)使用UDP传输数据

妖精的绣舞 提交于 2020-04-07 05:44:51

参考资料: UDP Socket 编程

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);	    
	}
}


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!