s-day11-UDP多发多收
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
package com.inmind.udp02;
|
||||
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
|
||||
//启动服务器,不停地获取客户端的信息
|
||||
public class UdpServerDemo05 {
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("服务器启动");
|
||||
//1.创建服务器对象
|
||||
DatagramSocket ds = new DatagramSocket(10023);
|
||||
//2.不停地获取数据包
|
||||
byte[] buffer = new byte[1024 * 64];
|
||||
while (true) {
|
||||
//3.创建出一个数据包,用于接收客户端的数据
|
||||
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
|
||||
//4.服务器正式接收数据包
|
||||
ds.receive(dp);
|
||||
//5.将字节数据转为字符,并显示对应客户端的信息
|
||||
int length = dp.getLength();//获取数据包中字节数据的长度
|
||||
String result = new String(buffer, 0, length);
|
||||
System.out.println(dp.getPort());//获取数据包的端口
|
||||
System.out.println(dp.getAddress().getHostAddress());//获取数据包的IP地址
|
||||
System.out.println(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user