解决浏览器不兼容websocket

本例使用tomcat 7.0的websocket做为例子。

1.新建web project。
2.找到tomcat 7.0 lib 下的 catalina.jar,tomcat-coyote.jar添加到项目中.
3.如下是我的目录结构


web.xml的配置.
[html]  view plain copy
 
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  5.     <display-name>Archetype Created Web Applicationdisplay-name>  
  6.     <servlet>  
  7.         <servlet-name>serverSocketservlet-name>  
  8.         <servlet-class>com.sun.websocket.server.ServerSocketservlet-class>  
  9.     servlet>  
  10.     <servlet-mapping>  
  11.         <servlet-name>serverSocketservlet-name>  
  12.         <url-pattern>/serverSocketurl-pattern>  
  13.     servlet-mapping>  
  14.       
  15.       <welcome-file-list>  
  16.         <welcome-file>index.jspwelcome-file>  
  17.       welcome-file-list>  
  18. web-app>  

ServerSocket.java的源码.
[java]  view plain copy
 
  1. package com.sun.websocket.server;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import java.nio.ByteBuffer;  
  6. import java.nio.CharBuffer;  
  7. import java.util.ArrayList;  
  8. import java.util.HashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11. import java.util.UUID;  
  12. import java.util.concurrent.ConcurrentHashMap;  
  13.   
  14. import javax.servlet.http.HttpServletRequest;  
  15.   
  16. import org.apache.catalina.websocket.MessageInbound;  
  17. import org.apache.catalina.websocket.StreamInbound;  
  18. import org.apache.catalina.websocket.WebSocketServlet;  
  19. import org.apache.catalina.websocket.WsOutbound;  
  20.   
  21. public class ServerSocket extends WebSocketServlet {  
  22.   
  23.     private static final long serialVersionUID = -4853540828121130946L;  
  24.     private static Map< String , MyMessageInbound> mmiList = new ConcurrentHashMap< String , MyMessageInbound >();  
  25.     private String message_to ;   
  26.     private String message_me ;   
  27.       
  28.     @Override  
  29.     protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) {  
  30.         message_me = request.getParameter( "message_me" );  
  31.         message_to = request.getParameter( "message_to" );  
  32.         return new MyMessageInbound();  
  33.     }  
  34.       
  35.     private class MyMessageInbound extends MessageInbound  {  
  36.         WsOutbound myoutbound;  
  37.         private String me = message_me ;   
  38.         private String to = message_to ;   
  39.   
  40.         @Override  
  41.         public void onOpen(WsOutbound outbound) {  
  42.             try {  
  43.                 System.out.println("Open " + me + " to " + to);  
  44.                 this.myoutbound = outbound;  
  45.                 mmiList.put( me , this );  
  46.                 outbound.writeTextMessage(CharBuffer.wrap("Hello!"));  
  47.             } catch (IOException e) {  
  48.                 e.printStackTrace();  
  49.             }  
  50.         }  
  51.   
  52.         @Override  
  53.         public void onTextMessage(CharBuffer cb) throws IOException {  
  54.             System.out.println("Accept Message : " + cb);  
  55.             for ( String mmib : mmiList.keySet() ) {  
  56.                 if ( !to.equals(mmib) )  
  57.                     continue;  
  58.                 try  
  59.                 {  
  60.                     CharBuffer buffer = CharBuffer.wrap(cb);  
  61.                     mmiList.get(mmib).myoutbound.writeTextMessage(buffer);  
  62.                     mmiList.get(mmib).myoutbound.flush();  
  63.                 }  
  64.                 catch (Exception e) {  
  65.                     continue;  
  66.                 }  
  67.                 break;  
  68.             }  
  69.         }  
  70.   
  71.         @Override  
  72.         public void onClose(int status) {  
  73.             if( status == 1002 || status == 1000)  
  74.             {  
  75.                 System.out.println("Close " + me + " to " + to);  
  76.                 mmiList.remove(this);  
  77.             }  
  78.         }  
  79.   
  80.         @Override  
  81.         public void onBinaryMessage(ByteBuffer bb) throws IOException {  
  82.         }  
  83.        
  84.     }  
  85. }  
接下来编写index.jsp
[html]  view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. >  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting pagetitle>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.       
  19.     <script type="text/javascript" src="scripts/swfobject.js">script>  
  20.     <script type="text/javascript" src="scripts/jquery.js">script>  
  21.     <script type="text/javascript" src="scripts/web_socket.js">script>  
  22.     <script type="text/javascript" src="scripts/jquery.WebSocket.js">script>  
  23.     <%  
  24.         String message_to = request.getParameter( "message_to" );  
  25.         String message_me = request.getParameter( "message_me" );  
  26.         request.setAttribute( "message_to" , message_to );  
  27.         request.setAttribute( "message_me" , message_me );  
  28.     %>  
  29. <script>  
  30.     $(function ()  
  31.     {  
  32.         window.onbeforeunload = onbeforeunload_handler;   
  33.         window.onunload = onunload_handler;   
  34.         function onbeforeunload_handler(){   
  35.             //ws.close();  
  36.             return warning;   
  37.         }  
  38.         function onunload_handler()  
  39.         {  
  40.             //alert(1);  
  41.             ws = null;  
  42.         }  
  43.     });  
  44.     var message_to = "${message_to}";  
  45.     var message_me = "${message_me}";  
  46.     //var ws = new WebSocket("ws://192.168.202.56:8080/websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me);  
  47.     var url = "websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me;  
  48.     var ws = new $.websocket({  
  49.         protocol : "websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me,  
  50.         domain : "192.168.1.120",  
  51.         port : "8080",  
  52.         onOpen:function(event){    
  53.             showMessage("已成功登录");    
  54.         },    
  55.         onError:function(event){  
  56.              alert("error:"+ event)  
  57.         },    
  58.         onMessage:function(result){    
  59.             receiveMessage(result);  
  60.         },  
  61.         onClose:function(event){  
  62.             ws = null;  
  63.         }  
  64.     });  
  65.       
  66.     function send(){  
  67.         if(!ws){  
  68.             alert("已经断开聊天室");  
  69.             return;  
  70.         }  
  71.          var msg=$.trim($("#msg").val());  
  72.          if(msg==""){return;}  
  73.          ws.send(msg);  
  74.          $("#messageInput").val("").focus();;  
  75.     }  
  76.       
  77.     function receiveMessage(result){  
  78.         showMessage(result);  
  79.     }  
  80.    
  81.     function showMessage(msg){  
  82.         document.getElementById("chatlog").textContent += msg + "\n";  
  83.     }  
  84. script>  
  85.   head>  
  86.     
  87.   <body>  
  88.     <body>  
  89.         <textarea id="chatlog" readonly style="width:500px;height:500px;">textarea><br/>  
  90.         <input id="msg" type="text" />  
  91.         <button type="submit" id="sendButton" onClick="send()">Send!button>  
  92.         <button type="submit" id="sendButton" onClick="closeConnect()">Endbutton>  
  93.     body>  
  94.   body>  
  95. html>  

编写完成后,访问index.jsp时需要URL给出两个参数。一个代表发送者,一个代表接收者。
[html]  view plain copy
 
  1. 例如 ?message_to=1&message_me=2"  
备注:具体需要的文件请到我的网盘下载:http://pan.baidu.com/s/1eQ1nbt4

你可能感兴趣的:(解决浏览器不兼容websocket)