java web工程启动socket服务

1、新建web工程

2、自定义类 实现ServletContextListener 接口

在contextInitialized方法中启动socket服务的线程

在contextDestroyed方法中关闭socket线程的服务,释放监听端口

3、更改web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_IDsocket Server</display-name>
  <context-param>
    <param-name>socketPort</param-name>
    <param-value>8888</param-value>
  </context-param>
  <listener>
    <description>Socket</description>
    <listener-class>myserver.ServerSocketListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

4、tomcat发布服务即可

 

注:需进入servlet-api.jar包

附示例代码

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(); 
        }
    }
}
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
        {
            Integer count = 0;
            while (!this.isInterrupted())
            {
                MyServer.rerfresh();
                
                Socket socket = serverSocket.accept();
                count++;
                System.out.println("Server SocketThread start:"+count);
                if (socket != null)
                {
                    SocketClientBean client = new SocketClientBean();
                    client.setSocket(socket);
                    MyServer.clientlist.add(client);

                    System.out.println("new commer:"+socket.getRemoteSocketAddress().toString());
                    MyServer.invoke(socket);
                }
            }
        }
        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());
        }
    }
}
public class MyServer
{
    public static List<SocketClientBean> clientlist = new ArrayList<SocketClientBean>();private static Timer timer = new Timer();

    public static void rerfresh()
    {
        timer.schedule(new MyClientRefreshTask(), 1000*0, 1000*15);
    }
    public static void destroyedTimer()
    {
        if(timer1!=null)
        {
            timer1.cancel();
        }
        if(timer!=null)
        {
            timer.cancel();
        }
    }
    
    public static void invoke(final Socket client) throws IOException
    {
        new Thread(new Runnable()
        {
            public void run()
            {
                String errcmd = "{\"cmd\":-1}";
                String nocmd = "{\"cmd\":0}";

                BufferedReader in = null;
                PrintWriter out = null;
                try
                {
                    in = new BufferedReader(new InputStreamReader(
                            client.getInputStream()));
                    out = new PrintWriter(client.getOutputStream());
                    Integer count = 0;
                    while (true)
                    {
                        String cmdmsg = in.readLine();
                        count++;
                        System.out.println(count);
                        System.out.println("Server received " + cmdmsg);

                        JSONObject jsmsg = JSONObject.fromObject(cmdmsg);
                        System.out.println("JSONObject success");
                        String cmd = jsmsg.getString("cmd");
                        switch (cmd)
                        {
                            case "1":
                                com.progress.cmd1.process(client, jsmsg);
                                break;
                            case "2":
                                com.progress.cmd2.process(client, jsmsg);
                                break;default:
                                out.println(nocmd);
                                out.flush();
                        }
                        if (cmdmsg.equals("bye"))
                        {
                            break;
                        }
                    }
                }
                catch (JSONException ex)
                {
                    System.out.println("JSONObject err");
                    out.println(errcmd);
                    out.flush();
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
                finally
                {
                    try
                    {
                        in.close();
                    }
                    catch (Exception e)
                    {
                    }
                    try
                    {
                        out.close();
                    }
                    catch (Exception e)
                    {
                    }
                    try
                    {
                        client.close();
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
        }).start();
    }
static class MyClientRefreshTask extends java.util.TimerTask
    {
        public void run()
        {
            refreshClient();
        }
    }
    private static void refreshClient()
    {
        List<SocketClientBean> dels = new ArrayList<SocketClientBean>();
        for (int i = 0; i < MyServer.clientlist.size(); i++)
        {
            if (MyServer.clientlist.get(i).getSocket().isClosed())
            {
                System.out.println("it is the del client!");
                dels.add(clientlist.get(i));
            }
        }
        System.out.println("clientlist num:"+clientlist.size());
        System.out.println("dels num:"+dels.size());
        clientlist.removeAll(dels);
        System.out.println("clientlist left num:"+clientlist.size());
    }

}

 

posted on 2013-08-29 17:40  ※WYF※  阅读(16247)  评论(1编辑  收藏  举报