解决浏览器不兼容websocket
本例使⽤tomcat 7.0的websocket做为例⼦。
1.新建web project。
2.到tomcat 7.0 lib 下的 catalina.jar,tomcat-coyote.jar添加到项⽬中.
3.如下是我的⽬录结构
[html]
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app version="2.5" xmlns="java.sun/xml/ns/javaee"
3. xmlns:xsi="/2001/XMLSchema-instance"
4. xsi:schemaLocation="java.sun/xml/ns/javaee java.sun/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.
15. <welcome-file-list>
16. <welcome-file>index.jsp</welcome-file>
17. </welcome-file-list>
18. </web-app>
ServerSocket.java的源码.
[java]
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 urrent.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 = Parameter( "message_me" );
31. message_to = Parameter( "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) {
43. System.out.println("Open " + me + " to " + to);
44. utbound = 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. (mmib).myoutbound.writeTextMessage(buffer);
62. (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. ve(this);
77. }
78. }
79.
80. @Override
81. public void onBinaryMessage(ByteBuffer bb) throws IOException {
82. }
83.
84. }
85. }
接下来编写index.jsp
[html]
1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2. <%
3. String path = ContextPath();
4. String basePath = Scheme()+"://"+ServerName()+":"+ServerPort()+path+"/";
5. %>
6.
7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
8. <html>
9. <head>
10. <base href="<%=basePath%>">
11.
12. <title>My JSP 'index.jsp' starting page</title>
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 = Parameter( "message_to" );
25. String message_me = Parameter( "message_me" );
26. request.setAttribute( "message_to" , message_to );
27. request.setAttribute( "message_me" , message_me );
28. %>
29. <script>
31. {
32. beforeunload = onbeforeunload_handler;
33. unload = 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. ElementById("chatlog").textContent += msg + "\n";
83. }
84. </script>
85. </head>
86.
87. <body>
88. <body>
89. <textarea id="chatlog" readonly ></textarea><br/>
90. <input id="msg" type="text" />websocket和socket
91. <button type="submit" id="sendButton" onClick="send()">Send!</button>
92. <button type="submit" id="sendButton" onClick="closeConnect()">End</button>
93. </body>
94. </body>
95. </html>
编写完成后,访问index.jsp时需要URL给出两个参数。⼀个代表发送者,⼀个代表接收者。
[html]
1. 例如 ?message_to=1&message_me=2"
备注:具体需要的⽂件请到我的⽹盘下载:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论