服务端代码:
public class UDPServer {
public static void main(String[] args) throws Exception{
InetAddress in= InetAddress.getLocalHost();
//1.创建一个DatagramSocket实例
DatagramSocket socket= new DatagramSocket(8800);
System.out.println("服务端启动成功");
int count=0;
while(true){
byte[] byte1= new byte[1024];
DatagramPacket packet= new DatagramPacket(
byte1, byte1.length, socket.getInetAddress(), 8888);
//当没有接收到数据是未阻塞状态
socket.receive(packet);
System.out.println(new String(byte1));
UDPThread thread= new UDPThread(socket);
thread.start();
count++;
System.out.println("当前连接的客服端的数量为:"+count);
}
}
}
线程处理类代码:
public class UDPThread extends Thread {
DatagramSocket socket = null;
public UDPThread(DatagramSocket socket) {
this.socket = socket;
}
// 重写run方法,一个处理的流程
public void run() {
try {
InetAddress in = InetAddress.getLocalHost();
byte[] by = "服务端欢迎你!".getBytes();
DatagramPacket packet2 = new DatagramPacket(by, by.length,
in.getLocalHost(), 8888);
System.out.println(in.getLocalHost());
//空
System.out.println(socket.getInetAddress());
//端口号?
System.out.println(socket.getLocalSocketAddress());
//0.0.0.0.0
System.out.println(socket.getLocalAddress());
// 发送
socket.send(packet2);
} catch (IOException e) {
e.printStackTrace();
}
}
客服端代码:
public class UDPClinet {
public static void main(String[] args) throws Exception {
InetAddress in=InetAddress.getLocalHost();
//发送数据到服务端
byte[] b="用户名:admin 密码:dn".getBytes();
DatagramPacket packet=new DatagramPacket(b, b.length, in.getLocalHost(), 8800);
DatagramSocket socket= new DatagramSocket(8888);
socket.send(packet);
//接收来自服务端响应的信息
byte[] by= new byte[1024];
DatagramPacket packet2= new DatagramPacket(by, 0, by.length, in.getLocalHost(),8800);
socket.receive(packet2);
//输出
System.out.println(new String(by));
socket.close();
}
}