자바,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=========");
  }
}
@SpringBootApplication
@ServletComponentScan 
public class DemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}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();
    }
  }
} 
 이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.