牛骨文教育服务平台(让学习变的简单)
博文笔记

WEBSOKET服务器搭建

创建时间:2013-06-27 投稿人: 浏览次数:5399

简单介绍一下tomcat的webSocketAPI使用:

在这里啰嗦几句:

很多朋友听说webSocket不知道是什么。知道是什么不知道怎么用,知道怎么用不知道具体实现。其实我当初也是这样。

实际上webSocket可以简单的理解为用浏览器与服务器简历socket连接,但是用了一个特殊的协议,偶收协议,它与http协议发送的报头不一样。

websocket需要服务器和浏览器支持,浏览器不支持,也就无法使用这个技术。服务器可以自己实现协议连接,但是我们不准备自己实现(其实看需求,至少对我来说不需要),当然目前javaEE官方不支持这个实现,没有规范(据说jsr356准备支持,期待来年【2013】javaEE7吧)

目前实现的java服务端第三方webSocketAPI不算少,比如jetty就是一种(多的我也举例不了,我只知道,没研究过有多少实现。)tomcat也自带了实现API

webSocket想要手动实现比较麻烦,可以看下tomcat实现过程,大致都一样。

总之一句话,webSocket是一种客户端与服务端连接socket的技术,实现即时消息,取代comet但是并没广泛只用,因为大多需要浏览器的支持,相对comet有很多优点,此处不举例说明。可以自己google一下。

 

tomcat7.027如何实现webSocket程序:

总的来说,实现webSocket的servlet要继承WebSocketServlet这个类。这个类是tomcat自己包装的servlet。

所有的入口都在protected StreamInbound createWebSocketInbound(String subProtocol) {}这个方法。 也就是说,我们实现这个方法,就可以实现握手协议了。

注意看这个方法。 要求返回StreamInbound类型。这个类型我们需要继承自己实现。打开源码观看这个类

有如下方法

 

Java代码  收藏代码
  1. /** 
  2.     * Intended to be overridden by sub-classes that wish to be notified 
  3.     * when the outbound connection is established. The default implementation 
  4.     * is a NO-OP. 
  5.     * 
  6.     * @param outbound    The outbound WebSocket connection. 
  7.     */  
  8.    protected void onOpen(WsOutbound outbound) {  
  9.        // NO-OP  
  10.    }  
  11.   
  12.    /** 
  13.     * Intended to be overridden by sub-classes that wish to be notified 
  14.     * when the outbound connection is closed. The default implementation 
  15.     * is a NO-OP. 
  16.     * 
  17.     * @param status    The status code of the close reason. 
  18.     */  
  19.    protected void onClose(int status) {  
  20.        // NO-OP  
  21.    }  
  22.   
  23.   
  24.    /** 
  25.     * This method is called when there is a binary WebSocket message available 
  26.     * to process. The message is presented via a stream and may be formed from 
  27.     * one or more frames. The number of frames used to transmit the message is 
  28.     * not made visible to the application. 
  29.     * 
  30.     * @param is    The WebSocket message 
  31.     * 
  32.     * @throws IOException  If a problem occurs processing the message. Any 
  33.     *                      exception will trigger the closing of the WebSocket 
  34.     *                      connection. 
  35.     */  
  36.    protected abstract void onBinaryData(InputStream is) throws IOException;  
  37.   
  38.   
  39.    /** 
  40.     * This method is called when there is a textual WebSocket message available 
  41.     * to process. The message is presented via a reader and may be formed from 
  42.     * one or more frames. The number of frames used to transmit the message is 
  43.     * not made visible to the application. 
  44.     * 
  45.     * @param r     The WebSocket message 
  46.     * 
  47.     * @throws IOException  If a problem occurs processing the message. Any 
  48.     *                      exception will trigger the closing of the WebSocket 
  49.     *                      connection. 
  50.     */  
  51.    protected abstract void onTextData(Reader r) throws IOException;  

 

  上面的方法都是要我们自己实现的。tomcat没有给我们实现。

仔细看都是onXxx格式,类似事件监听。其实也差不多。只是tomcat在得到消息或者链接发生变化的时候会去调用这些方法,实现方法“自动”触发。

仔细看源码还有很多函数可以使用,这里不一一介绍。感兴趣可以打开源码看看。

其实仔细看官方的例子,chat那个例子也能得到这个结论(tomcat的webSocket例子需要tomcat7.027才带有)

我们定义一个servlet

 

Java代码  收藏代码
  1. @WebServlet(urlPatterns = { "/chatWebSocket" })  
  2. public class ChatWebSocketServlet extends WebSocketServlet {  
  3.   
  4.     private static final long serialVersionUID = 1L;  
  5.     OnLineUser theUser;  
  6.   
  7.     @Override  
  8.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  9.             throws ServletException, IOException {  
  10.         theUser = (OnLineUser) req.getSession().getAttribute("loginUser");  
  11.         super.doGet(req, resp);  
  12.     }  
  13.   
  14.     @Override  
  15.     protected StreamInbound createWebSocketInbound(String subProtocol) {  
  16.         return new ChatMessageInbound(theUser);  
  17.     }  
  18.   
  19. }  

 

 doget不用说,是连接的开始,然后取出登录的用户,这个是为了管理连接使用的,你在看这个例子的时候不需要doget方法和theUser声明,只要有createWebSocketInbound方法就行。上面说了。这个方法是webSocket的入口。其实也是WebSocketServlet这个类写好的doget,我们看WebSocketServlet的doget是如何写的

Java代码  收藏代码
  1. @Override  
  2.    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  3.            throws ServletException, IOException {  
  4.   
  5.        // Information required to send the server handshake message  
  6.        String key;  
  7.        String subProtocol = null;  
  8.        List<String> extensions = Collections.emptyList();  
  9.   
  10.        if (!headerContainsToken(req, "upgrade", "websocket")) {  
  11.            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);  
  12.            return;  
  13.        }  
  14.   
  15.        if (!headerContainsToken(req, "connection", "upgrade")) {  
  16.            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);  
  17.            return;  
  18.        }  
  19.   
  20.        if (!headerContainsToken(req, "sec-websocket-version", "13")) {  
  21.            resp.setStatus(426);  
  22.            resp.setHeader("Sec-WebSocket-Version", "13");  
  23.            return;  
  24.        }  
  25.   
  26.        key = req.getHeader("Sec-WebSocket-Key");  
  27.        if (key == null) {  
  28.            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);  
  29.            return;  
  30.        }  
  31.   
  32.        String origin = req.getHeader("Origin");  
  33.        if (!verifyOrigin(origin)) {  
  34.            resp.sendError(HttpServletResponse.SC_FORBIDDEN);  
  35.            return;  
  36.        }  
  37.   
  38.        List<String> subProtocols = getTokensFromHeader(req,  
  39.                "Sec-WebSocket-Protocol-Client");  
  40.        if (!subProtocols.isEmpty()) {  
  41.            subProtocol = selectSubProtocol(subProtocols);  
  42.   
  43.        }  
  44.   
  45.        // TODO Read client handshake - Sec-WebSocket-Extensions  
  46.   
  47.        // TODO Extensions require the ability to specify something (API TBD)  
  48.        //      that can be passed to the Tomcat internals and process extension  
  49.        //      data present when the frame is fragmented.  
  50.   
  51.        // If we got this far, all is good. Accept the connection.  
  52.        resp.setHeader("upgrade", "websocket");  
  53.        resp.setHeader("connection", "upgrade");  
  54.        resp.setHeader("Sec-WebSocket-Accept", getWebSocketAccept(key));  
  55.        if (subProtocol != null) {  
  56.            resp.setHeader("Sec-WebSocket-Protocol", subProtocol);  
  57.        }  
  58.        if (!extensions.isEmpty()) {  
  59.            // TODO  
  60.        }  
  61.   
  62.        // Small hack until the Servlet API provides a way to do this.  
  63.        StreamInbound inbound = createWebSocketInbound(subProtocol);  
  64.        ((RequestFacade) req).doUpgrade(inbound);  
  65.    }  
 

注意倒数第三行,调用了createWebSocketInbound方法,我们重写这个方法。

Java代码  收藏代码
  1. @Override  
  2.     protected StreamInbound createWebSocketInbound(String subProtocol) {  
  3.         return new ChatMessageInbound(theUser);  
  4.     }  

上面的ChatMessageInbound是我自己定义的继承类。

Java代码  收藏代码
  1. public final class ChatMessageInbound extends MessageInbound {  
  2.   
  3.     public ChatMessageInbound(OnLineUser theUser) {  
  4.         this.theUser = theUser;  
  5.     }  
  6.   
  7.     @Override  
  8.     protected void onOpen(WsOutbound outbound) {  
  9.         // 添加链接到容器  
  10.         ChatMessageInbound theBound = this;  
  11.         ChatContainer.addInbound(theBound.theUser, theBound);  
  12.         // 向每个在线用户发送消息  
  13.         ChatContainer.eachAllBound(new ContainerCallBack() {  
  14.             @Override  
  15.             public void eachCallBack(ChatMessageInbound theBound, OnLineUser theUser) {  
  16.                 ListUserMsg listUserMsg = new ListUserMsg(ChatContainer.getUserList());  
  17.                 WriteTookit.writeToBound(theBound, listUserMsg.toMsg());  
  18.             }  
  19.         });  
  20.     }  
  21.   
  22.     @Override  
  23.     protected void onClose(int status) {  
  24.         ChatContainer.removeInbound(theUser);  
  25.     }  
  26.   
  27.     @Override  
  28.     protected void onBinaryMessage(ByteBuffer message) throws IOException {  
  29.     }  
  30.   
  31.     @Override  
  32.     protected void onTextMessage(CharBuffer message) throws IOException {  
  33. //      CHAT_MODEL.setMessage(message.toString());  
  34. //      ChatContainer.eachAllBound(new ContainerCallBack() {  
  35. //          @Override  
  36. //          public void eachCallBack(ChatMessageInbound theBound, OnLineUser theUser) {  
  37. //              WriteTookit.writeToBound(theBound, CHAT_MODEL.getSayMsg());  
  38. //          }  
  39. //      });  
  40.     }  
  41.   
  42.     // 变量区域  
  43.     private OnLineUser theUser;  
  44. }  

 这里只是简单实现了一下,注释部分只是处理这个方法的部分,那里是一个容器,存档所有在线用户。并且提供遍历插入以及删除等方法,在自己实现的时候完全不需要这么写。

下面是容器代码

 

Java代码  收藏代码
  1. public final class ChatContainer {  
  2.     /** 
  3.      * 保存服务器连接的用户的容器 
  4.      */  
  5.     private static final Map<OnLineUser, ChatMessageInbound> CHAT_MAP = new HashMap<OnLineUser, ChatMessageInbound>();  
  6.   
  7.     /** 
  8.      * 取出用户的连接 
  9.      */  
  10.     public static ChatMessageInbound getInbound(OnLineUser theUser) {  
  11.         return CHAT_MAP.get(theUser);  
  12.     }  
  13.   
  14.     /** 
  15.      * 放入一个连接 
  16.      */  
  17.     public static void addInbound(OnLineUser theUser,  
  18.             ChatMessageInbound outbound) {  
  19.         CHAT_MAP.put(theUser, outbound);  
  20.         System.out.println(CHAT_MAP.size());  
  21.     }  
  22.   
  23.     /** 
  24.      * 移除一个连接 
  25.      *  
  26.      * @param theUser 
  27.      * @return 
  28.      */  
  29.     public static ChatMessageInbound removeInbound(OnLineUser theUser) {  
  30.         return CHAT_MAP.remove(theUser);  
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。