web socket多线程实时监听
Posted 一棵小草77
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了web socket多线程实时监听相关的知识,希望对你有一定的参考价值。
配置文件:
web.xml文件: <!-- socket 监听 --> <context-param> <param-name>socketPort</param-name> <param-value>8888</param-value> </context-param> <listener> <description>Socket</description> <listener-class>com.demo.modules.intf.listener.ServerSocketListener</listener-class> </listener>
代码:
package com.demo.modules.intf.listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.demo.intf.util.SocketThread; public class ServerSocketListener implements ServletContextListener { private SocketThread socketThread; public void contextDestroyed(ServletContextEvent e) { if (socketThread != null && socketThread.isInterrupted()) { socketThread.closeServerSocket(); socketThread.interrupt(); } } public void contextInitialized(ServletContextEvent e) { ServletContext servletContext = e.getServletContext(); System.out.println("Server contextInitialized over"); if (socketThread == null) { socketThread = new SocketThread(null, servletContext); socketThread.start(); } } } ---------------------------- package com.demo.intf.util; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.servlet.ServletContext; public class SocketThread extends Thread { Integer count = 0; private ServletContext servletContext; private ServerSocket serverSocket; public SocketThread(ServerSocket serverSocket, ServletContext servletContext) { this.servletContext = servletContext; // 从web.xml中context-param节点获取socket端口 String port = this.servletContext.getInitParameter("socketPort"); if (serverSocket == null) { try { this.serverSocket = new ServerSocket(Integer.parseInt(port)); } catch (IOException e) { e.printStackTrace(); } } } public void run() { try { Socket client = null; //通过调用Executors类的静态方法,创建一个ExecutorService实例 //ExecutorService接口是Executor接口的子接口 Executor service = Executors.newCachedThreadPool(); Integer count = 0; while (!this.isInterrupted()) { client = serverSocket.accept(); count++; System.out.println("Server SocketThread start:"+count); if (client != null) { //调用execute()方法时,如果必要,会创建一个新的线程来处理任务,但它首先会尝试使用已有的线程, //如果一个线程空闲60秒以上,则将其移除线程池; //另外,任务是在Executor的内部排队,而不是在网络中排队 service.execute(new ServerThread(client)); } } } catch (Exception ex) { System.out.println("SocketThread err:"+ex.getMessage()); } } public void closeServerSocket() { try { if (serverSocket != null && !serverSocket.isClosed()) { serverSocket.close(); MyServer.destroyedTimer(); } } catch (Exception ex) { System.out.println("SocketThread err:"+ex.getMessage()); } } }
以上是关于web socket多线程实时监听的主要内容,如果未能解决你的问题,请参考以下文章