UDP协议实现接受发送数据

web项目使用udp实现客户端和服务端,发送和接收数据,需要在启动容器的时候创建DatagramSocket,并使它一直处于阻塞状态——直到有接收消息。所以我们要开启另外一个线程,客户端发送数据包的时候须指定接收端的ip和端口

1定义监听器

public class SocketServiceLoader implements ServletContextListener {

private Thread thread;

// 线程销毁

publicvoid contextDestroyed(ServletContextEvent sce) {

if (thread != null && thread.isInterrupted()) {

thread.interrupt();

}

}

// 线程启动

publicvoid contextInitialized(ServletContextEventsce) {

if (thread == null) {

SocketOperate socketOperate = new SocketOperate();

thread = new Thread(socketOperate);

thread.start();

}

}

}

2添加web.xml配置

<listener>

<listener-class>com.shuodao.cokeps.socket.SocketServiceLoader</listener-class>

</listener>

3创建一个线程,并作为服务端接收数据

public class SocketOperate extends Thread {

privatefinal Logger logger = LoggerFactory.getLogger(SocketOperate.class);

static Queue<String> queue = new LinkedList<String>();

publicstatic Queue<String> getQueue() {

returnqueue;

}

publicvoid run() {

// 准备空包

byte[] buf = newbyte[1024];

// 解析数据包

DatagramPacket packet = new DatagramPacket(buf, buf.length);

// 准备socket

DatagramSocket socket = null;

try {

socket = new DatagramSocket(8086);

while (true) {

// 接收数据包

logger.info(“阻塞”);

socket.receive(packet);

logger.info(“疏通”);

String ip = packet.getAddress().getHostAddress();

buf = packet.getData();

String data = new String(buf, 0, packet.getLength());

queue.add(data);

logger.info(“收到 ” + ip + ” 发来的消息:” + data);

}

} catch (SocketException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

socket.close();

}

}

}

 

4可以使用测试客户端实现发送数据

public static void main(String[] args) throws SocketException {

DatagramSocket socket = new DatagramSocket();

try {

String s = getJsonStr();

byte[] buf = s.getBytes();

//将数据打包

DatagramPacket packet; //114.55.233.51

packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(“127.0.0.1”), 8086);

socket.send(packet);

} catch (Exception e) {

e.printStackTrace();

} finally {

socket.close();

}

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注