Java 实现简单的UDP通信

创建服务器:

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

public class TestUDPServer {
	public static void main(String args[]){
		byte[] buf=new byte[1024];
		DatagramPacket dp=null;
		DatagramSocket ds=null;
	    dp=new DatagramPacket(buf,buf.length);//创建一个数据包裹,用字节数组buf来接收数据
		try {
			ds=new DatagramSocket(6666);//创建数据报套接字并将其绑定到6666的本机端口
		} catch (SocketException e) {
			e.printStackTrace();
		}
		while(true){
			try {
				ds.receive(dp);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println(new String(buf,0,dp.getLength()));
		}
	}

}

创建客户端:

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

public class TestUDPClient {

	public static void main(String[] args) {
		byte[] buf=new String("hellow").getBytes();
		DatagramPacket dp=null;
		try {
			dp=new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",6666));
		} catch (SocketException e) {
			e.printStackTrace();
		}
        DatagramSocket ds=null;
        try {
			ds=new DatagramSocket(8888);
		} catch (SocketException e) {
			e.printStackTrace();
		}
        try {
			ds.send(dp);
		} catch (IOException e) {
			e.printStackTrace();
		}
        ds.close();
	}

}


你可能感兴趣的:(Java)