Java基于ServletContextListener实现UDP监听

这篇文章主要介绍了Java基于ServletContextListener实现UDP监听,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

目前创新互联已为成百上千的企业提供了网站建设、域名、雅安服务器托管网站托管运营、企业网站设计、临川网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

使用spring boot实现项目启动时的监听,

UDPListener

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

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class UDPListener implements ServletContextListener {

  public static final int MAX_UDP_DATA_SIZE = 4096;
  public static final int UDP_PORT = 26666;

  @Override
  public void contextInitialized(ServletContextEvent sce) {

    System.out.println("========UDPListener Initialized=========");
    try {
       // 启动一个线程,监听UDP数据报
      new Thread(new UDPProcess(UDP_PORT)).start();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  class UDPProcess implements Runnable {
    DatagramSocket socket = null;

    public UDPProcess(final int port) throws SocketException {
      socket = new DatagramSocket(port);
    }

    @Override
    public void run() {
      // TODO Auto-generated method stub
      System.out.println("=======UDPProcess======");
      while (true) {
        byte[] buffer = new byte[MAX_UDP_DATA_SIZE];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        try {
          socket.receive(packet);
          new Thread(new Process(packet)).start();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

    }
  }

  class Process implements Runnable {

    public Process(DatagramPacket packet) throws UnsupportedEncodingException {
      // TODO Auto-generated constructor stub
      byte[] buffer = packet.getData();// 接收到的UDP信息,然后解码
      String srt1 = new String(buffer,"GBK").trim();
      String srt2 = new String(buffer, "UTF-8").trim();
      String srt3 = new String(buffer,"ISO-8859-1").trim();
      System.out.println("=======Process srt1 GBK======" + srt1);
      System.out.println("=======Process srt2 UTF-8======" + srt2);
      System.out.println("=======Process srt3 ISO-8859-1======" + srt3);
    }

    @Override
    public void run() {
      // TODO Auto-generated method stub
      System.out.println("====Process run=====");
    }
    
  }

  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    System.out.println("========UDPListener Destroyed=========");
  }

}

DemoApplication

@SpringBootApplication
@ServletComponentScan 
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

@ServletComponentScan Servlet扫描,启动时把servlet、filter、listener自动扫描注入

UDP测试客户端(也可以用测试工具发送UDP包测试):

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClientTest {

  public static final String SERVER_HOSTNAME = "localhost";
  // 服务器端口
  public static final int SERVER_PORT = 26666;
  // 本地发送端口
  public static final int LOCAL_PORT = 8888;

  public static void main(String[] args) {
    try {
      // 1,创建udp服务。通过DatagramSocket对象。
      DatagramSocket socket = new DatagramSocket(LOCAL_PORT);
      // 2,确定数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress
      // address, int port)
      byte[] buf = "你好,世界".getBytes();
      DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(SERVER_HOSTNAME),
          SERVER_PORT);
      // 3,通过socket服务,将已有的数据包发送出去。通过send方法。
      socket.send(dp);
      // 4,关闭资源。
      socket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

结果:

Java基于ServletContextListener实现UDP监听

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


名称栏目:Java基于ServletContextListener实现UDP监听
当前网址:http://hbruida.cn/article/ggiosp.html