UDP实现服务器与客户端双向通信

package UDPconnection;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPserver 
{
	public static void main(String args[]) throws Exception
	{
		DatagramSocket socket=new DatagramSocket();
		String str="nice to meet you!";
		//构造数据报包
		DatagramPacket packet =new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),5000);
		//发送
		socket.send(packet);
		
		byte []by=new byte[1024];
		DatagramPacket repacket=new DatagramPacket(by,100);
		socket.receive(repacket);
		System.out.println(new String(by,0,repacket.getLength()));
		socket.close();
	}

package UDPconnection;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPclient 
{
	public static void main(String args[]) throws Exception
	{
		byte[] by=new byte[1024];
		DatagramSocket socket=new DatagramSocket(7000);
		DatagramPacket repacket=new DatagramPacket(by,by.length);
		socket.receive(repacket);
		System.out.println(new String(by,0,repacket.getLength()));
		String str="I love You!";
		DatagramPacket packet=new DatagramPacket(str.getBytes(),str.length(),repacket.getAddress(),repacket.getPort());
		
		socket.send(packet);
		socket.close();
	}
}

你可能感兴趣的:(java)