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

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


web.xml的配置.
  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 Application</display-name>
  6. <servlet>
  7. <servlet-name>serverSocket</servlet-name>
  8. <servlet-class>com.sun.websocket.server.ServerSocket</servlet-class>
  9. </servlet>
  10. <servlet-mapping>
  11. <servlet-name>serverSocket</servlet-name>
  12. <url-pattern>/serverSocket</url-pattern>
  13. </servlet-mapping>
  14. <welcome-file-list>
  15. <welcome-file>index.jsp</welcome-file>
  16. </welcome-file-list>
  17. </web-app>

ServerSocket.java的源码.

  1. package com.sun.websocket.server;
  2. import java.io.IOException;
  3. import java.nio.ByteBuffer;
  4. import java.nio.CharBuffer;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.UUID;
  10. import java.util.concurrent.ConcurrentHashMap;
  11. import javax.servlet.http.HttpServletRequest;
  12. import org.apache.catalina.websocket.MessageInbound;
  13. import org.apache.catalina.websocket.StreamInbound;
  14. import org.apache.catalina.websocket.WebSocketServlet;
  15. import org.apache.catalina.websocket.WsOutbound;
  16. public class ServerSocket extends WebSocketServlet {
  17. private static final long serialVersionUID = -4853540828121130946L;
  18. private static Map< String , MyMessageInbound> mmiList = new ConcurrentHashMap< String , MyMessageInbound >();
  19. private String message_to ;
  20. private String message_me ;
  21. @Override
  22. protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) {
  23. message_me = request.getParameter( "message_me" );
  24. message_to = request.getParameter( "message_to" );
  25. return new MyMessageInbound();
  26. }
  27. private class MyMessageInbound extends MessageInbound  {
  28. WsOutbound myoutbound;
  29. private String me = message_me ;
  30. private String to = message_to ;
  31. @Override
  32. public void onOpen(WsOutbound outbound) {
  33. try {
  34. System.out.println("Open " + me + " to " + to);
  35. this.myoutbound = outbound;
  36. mmiList.put( me , this );
  37. outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. @Override
  43. public void onTextMessage(CharBuffer cb) throws IOException {
  44. System.out.println("Accept Message : " + cb);
  45. for ( String mmib : mmiList.keySet() ) {
  46. if ( !to.equals(mmib) )
  47. continue;
  48. try
  49. {
  50. CharBuffer buffer = CharBuffer.wrap(cb);
  51. mmiList.get(mmib).myoutbound.writeTextMessage(buffer);
  52. mmiList.get(mmib).myoutbound.flush();
  53. }
  54. catch (Exception e) {
  55. continue;
  56. }
  57. break;
  58. }
  59. }
  60. @Override
  61. public void onClose(int status) {
  62. if( status == 1002 || status == 1000)
  63. {
  64. System.out.println("Close " + me + " to " + to);
  65. mmiList.remove(this);
  66. }
  67. }
  68. @Override
  69. public void onBinaryMessage(ByteBuffer bb) throws IOException {
  70. }
  71. }
  72. }

接下来编写index.jsp

  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. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <base href="<%=basePath%>">
  10. <title>My JSP 'index.jsp' starting page</title>
  11. <meta http-equiv="pragma" content="no-cache">
  12. <meta http-equiv="cache-control" content="no-cache">
  13. <meta http-equiv="expires" content="0">
  14. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  15. <meta http-equiv="description" content="This is my page">
  16. <script type="text/javascript" src="scripts/swfobject.js"></script>
  17. <script type="text/javascript" src="scripts/jquery.js"></script>
  18. <script type="text/javascript" src="scripts/web_socket.js"></script>
  19. <script type="text/javascript" src="scripts/jquery.WebSocket.js"></script>
  20. <%
  21. String message_to = request.getParameter( "message_to" );
  22. String message_me = request.getParameter( "message_me" );
  23. request.setAttribute( "message_to" , message_to );
  24. request.setAttribute( "message_me" , message_me );
  25. %>
  26. <script>
  27. $(function ()
  28. {
  29. window.onbeforeunload = onbeforeunload_handler;
  30. window.onunload = onunload_handler;
  31. function onbeforeunload_handler(){
  32. //ws.close();
  33. return warning;
  34. }
  35. function onunload_handler()
  36. {
  37. //alert(1);
  38. ws = null;
  39. }
  40. });
  41. var message_to = "${message_to}";
  42. var message_me = "${message_me}";
  43. //var ws = new WebSocket("ws://192.168.202.56:8080/websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me);
  44. var url = "websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me;
  45. var ws = new $.websocket({
  46. protocol : "websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me,
  47. domain : "192.168.1.120",
  48. port : "8080",
  49. onOpen:function(event){
  50. showMessage("已成功登录");
  51. },
  52. onError:function(event){
  53. alert("error:"+ event)
  54. },
  55. onMessage:function(result){
  56. receiveMessage(result);
  57. },
  58. onClose:function(event){
  59. ws = null;
  60. }
  61. });
  62. function send(){
  63. if(!ws){
  64. alert("已经断开聊天室");
  65. return;
  66. }
  67. var msg=$.trim($("#msg").val());
  68. if(msg==""){return;}
  69. ws.send(msg);
  70. $("#messageInput").val("").focus();;
  71. }
  72. function receiveMessage(result){
  73. showMessage(result);
  74. }
  75. function showMessage(msg){
  76. document.getElementById("chatlog").textContent += msg + "\n";
  77. }
  78. </script>
  79. </head>
  80. <body>
  81. <body>
  82. <textarea id="chatlog" readonly style="width:500px;height:500px;"></textarea><br/>
  83. <input id="msg" type="text" />
  84. <button type="submit" id="sendButton" onClick="send()">Send!</button>
  85. <button type="submit" id="sendButton" onClick="closeConnect()">End</button>
  86. </body>
  87. </body>
  88. </html>

编写完成后,访问index.jsp时需要URL给出两个参数。一个代表发送者,一个代表接收者。

  1. 例如 ?message_to=1&message_me=2"
备注:具体需要的文件请到我的网盘下载:http://pan.baidu.com/s/1eQ1nbt4

解决浏览器不兼容websocket的更多相关文章

  1. jsp关闭或刷新浏览器(解决浏览器不兼容),请求后台onbeforeunload、onunload

    jsp关闭或刷新浏览器(解决浏览器不兼容),请求后台  onbeforeunload.onunload 1.看代码: function test(e) { var json = "退出,清理 ...

  2. html5--4-3 source元素-解决浏览器的兼容

    html5--4-3 source元素-解决浏览器的兼容 学习要点 掌握source元素的用法 source元素-解决浏览器额兼容 HTML5 中新增的元素 video和audio元素的子元素,可指定 ...

  3. js复制当前url地址解决浏览器兼容

    1.网上搜索的js复制链接代码,好像只能支持ie浏览器,其他浏览器不支持, 案例: var url=12; if(window.clipboardData){                   wi ...

  4. IE内嵌google chrome frame解决浏览器兼容问题

    IE内嵌google chrome frame解决浏览器兼容问题  http://www.cnblogs.com/xwdreamer/archive/2013/12/17/3477776.html 参 ...

  5. 教你一招解决浏览器兼容问题(PostCSS的使用)

    我们在处理网页的时候,往往会遇到兼容性的问题.在这个问题上分为两个大的方向:屏幕自适应&浏览器兼容.而屏幕自使用的方法有许多,包括框架之类的,但是浏览器的兼容却没有一个号的框架.在我们日常处理 ...

  6. 一行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10

    行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10 2012-04-25 16:29:04| 分类: 学习 |字号 订阅 在网站开发中不免因为各种兼容问题苦恼,针对兼容问题,其实IE ...

  7. CSS Hack解决浏览器IE部分属性兼容性问题

    1.Css Hack 不同厂商的流览器或某浏览器的不同版本(如IE6-IE11,Firefox/Safari/Opera/Chrome等),对CSS的支持.解析不一样,导致在不同浏览器的环境中呈现出不 ...

  8. 一行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10 http://www.jb51.net/css/383986.html

    在网站开发中不免因为各种兼容问题苦恼,针对兼容问题,其实IE给出了解决方案Google也给出了解决方案百度也应用了这种方案去解决IE的兼容问题   百度源代码如下 复制代码 代码如下: <!Do ...

  9. 复制到剪贴板的JS实现--ZeroClipboard (兼解决IE下兼容问题)

    复制到剪贴板的JS实现--ZeroClipboard (兼解决IE下兼容问题) 相信绝大多数人都遇到过这样的功能实现,“复制”或者“复制到剪贴板”这样的功能.但是由于各大浏览器的实现方案不一样,导致几 ...

随机推荐

  1. org.mybatis.spring.mapper.MapperScannerConfigurer$Scanner$1

    不能加载或找不到 org.mybatis.spring.mapper.MapperScannerConfigurer$Scanner$1 经查证,是mybatis-spring-xxx.jar 这个版 ...

  2. pigofzhou的巧克力棒

    Description 众所周知,pigofzhou有许多妹子.有一天,pigofzhou得到了一根巧克力棒,他想把这根巧克力棒分给他的妹子们.具体地,这根巧克力棒长为 n,他想将这根巧克力棒折成 n ...

  3. mysql分页小结

    mysql.select('*').from('books') .join('cSessionInfo', 'books.openid', 'cSessionInfo.open_id') .limit ...

  4. 【hdu 1429】胜利大逃亡(续)

    [Link]: [Description] 给你一个n*m的格子; 里面有钥匙,以及钥匙能开的门; 以及墙,以及起点,以及出口; 问你从起点出发,到出口的话,能不能在t时间内到; [Solution] ...

  5. 11.2.0.1升级到11.2.0.4报错之中的一个:UtilSession failed: Patch 9413827

    UtilSession failed: Patch 9413827 requires component(s) that are not installed in OracleHome. These ...

  6. [Python] Manipulate Data with Dictionaries in Python

    Dictionaries may be familiar to you as hash maps. In this lesson, you will learn how to create them, ...

  7. [ES6] The Iterator Protocol

    The iterator protocol is used to define a standard way that an object produces a sequence of values. ...

  8. /dev/shm和swap差别与联系

    1.基本理论 /dev/shm这个文件是寄生虫,寄存在内存中 swap是暂时在硬盘中划分一个区域,把它作为内存使用 2.怎样查看 使用df -lh能够查看/dev/shm 使用free -m能够查看s ...

  9. 正确地在QML应用中使用fontsize

    我们知道我们有时须要显示text文本.可是,在QML应用中.我们应该怎样选择font的大小呢?在今天的这篇文章中,我们将展示在Ubuntu平台中的不同文字的大小.我们能够通过FontUtils来帮我们 ...

  10. Es61

    ECMAScript和JavaScript的关系 ECMAScript 6(以下简称ES6)是JavaScript语言的下一代标准,已经在2015年6月正式发布了.Mozilla公司将在这个标准的基础 ...