解决浏览器不兼容websocke原文地址thttp://www.bieryun.com/935.html
本例使用tomcat 7.0的websocket做为例子。
1.新建web project。
2.找到tomcat 7.0 lib 下的 catalina.jar,tomcat-coyote.jar添加到项目中.
3.如下是我的目录结构
web.xml的配置.
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name>Archetype Created Web Application</display-name>
- <servlet>
- <servlet-name>serverSocket</servlet-name>
- <servlet-class>com.sun.websocket.server.ServerSocket</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>serverSocket</servlet-name>
- <url-pattern>/serverSocket</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
ServerSocket.java的源码.
- package com.sun.websocket.server;
- import java.io.IOException;
- import java.nio.ByteBuffer;
- import java.nio.CharBuffer;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.UUID;
- import java.util.concurrent.ConcurrentHashMap;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.catalina.websocket.MessageInbound;
- import org.apache.catalina.websocket.StreamInbound;
- import org.apache.catalina.websocket.WebSocketServlet;
- import org.apache.catalina.websocket.WsOutbound;
- public class ServerSocket extends WebSocketServlet {
- private static final long serialVersionUID = -4853540828121130946L;
- private static Map< String , MyMessageInbound> mmiList = new ConcurrentHashMap< String , MyMessageInbound >();
- private String message_to ;
- private String message_me ;
- @Override
- protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) {
- message_me = request.getParameter( "message_me" );
- message_to = request.getParameter( "message_to" );
- return new MyMessageInbound();
- }
- private class MyMessageInbound extends MessageInbound {
- WsOutbound myoutbound;
- private String me = message_me ;
- private String to = message_to ;
- @Override
- public void onOpen(WsOutbound outbound) {
- try {
- System.out.println("Open " + me + " to " + to);
- this.myoutbound = outbound;
- mmiList.put( me , this );
- outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onTextMessage(CharBuffer cb) throws IOException {
- System.out.println("Accept Message : " + cb);
- for ( String mmib : mmiList.keySet() ) {
- if ( !to.equals(mmib) )
- continue;
- try
- {
- CharBuffer buffer = CharBuffer.wrap(cb);
- mmiList.get(mmib).myoutbound.writeTextMessage(buffer);
- mmiList.get(mmib).myoutbound.flush();
- }
- catch (Exception e) {
- continue;
- }
- break;
- }
- }
- @Override
- public void onClose(int status) {
- if( status == 1002 || status == 1000)
- {
- System.out.println("Close " + me + " to " + to);
- mmiList.remove(this);
- }
- }
- @Override
- public void onBinaryMessage(ByteBuffer bb) throws IOException {
- }
- }
- }
接下来编写index.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <script type="text/javascript" src="scripts/swfobject.js"></script>
- <script type="text/javascript" src="scripts/jquery.js"></script>
- <script type="text/javascript" src="scripts/web_socket.js"></script>
- <script type="text/javascript" src="scripts/jquery.WebSocket.js"></script>
- <%
- String message_to = request.getParameter( "message_to" );
- String message_me = request.getParameter( "message_me" );
- request.setAttribute( "message_to" , message_to );
- request.setAttribute( "message_me" , message_me );
- %>
- <script>
- $(function ()
- {
- window.onbeforeunload = onbeforeunload_handler;
- window.onunload = onunload_handler;
- function onbeforeunload_handler(){
- //ws.close();
- return warning;
- }
- function onunload_handler()
- {
- //alert(1);
- ws = null;
- }
- });
- var message_to = "${message_to}";
- var message_me = "${message_me}";
- //var ws = new WebSocket("ws://192.168.202.56:8080/websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me);
- var url = "websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me;
- var ws = new $.websocket({
- protocol : "websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me,
- domain : "192.168.1.120",
- port : "8080",
- onOpen:function(event){
- showMessage("已成功登录");
- },
- onError:function(event){
- alert("error:"+ event)
- },
- onMessage:function(result){
- receiveMessage(result);
- },
- onClose:function(event){
- ws = null;
- }
- });
- function send(){
- if(!ws){
- alert("已经断开聊天室");
- return;
- }
- var msg=$.trim($("#msg").val());
- if(msg==""){return;}
- ws.send(msg);
- $("#messageInput").val("").focus();;
- }
- function receiveMessage(result){
- showMessage(result);
- }
- function showMessage(msg){
- document.getElementById("chatlog").textContent += msg + "\n";
- }
- </script>
- </head>
- <body>
- <body>
- <textarea id="chatlog" readonly style="width:500px;height:500px;"></textarea><br/>
- <input id="msg" type="text" />
- <button type="submit" id="sendButton" onClick="send()">Send!</button>
- <button type="submit" id="sendButton" onClick="closeConnect()">End</button>
- </body>
- </body>
- </html>
编写完成后,访问index.jsp时需要URL给出两个参数。一个代表发送者,一个代表接收者。
- 例如 ?message_to=1&message_me=2"
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name>Archetype Created Web Application</display-name>
- <servlet>
- <servlet-name>serverSocket</servlet-name>
- <servlet-class>com.sun.websocket.server.ServerSocket</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>serverSocket</servlet-name>
- <url-pattern>/serverSocket</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
ServerSocket.java的源码.
- package com.sun.websocket.server;
- import java.io.IOException;
- import java.nio.ByteBuffer;
- import java.nio.CharBuffer;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.UUID;
- import java.util.concurrent.ConcurrentHashMap;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.catalina.websocket.MessageInbound;
- import org.apache.catalina.websocket.StreamInbound;
- import org.apache.catalina.websocket.WebSocketServlet;
- import org.apache.catalina.websocket.WsOutbound;
- public class ServerSocket extends WebSocketServlet {
- private static final long serialVersionUID = -4853540828121130946L;
- private static Map< String , MyMessageInbound> mmiList = new ConcurrentHashMap< String , MyMessageInbound >();
- private String message_to ;
- private String message_me ;
- @Override
- protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) {
- message_me = request.getParameter( "message_me" );
- message_to = request.getParameter( "message_to" );
- return new MyMessageInbound();
- }
- private class MyMessageInbound extends MessageInbound {
- WsOutbound myoutbound;
- private String me = message_me ;
- private String to = message_to ;
- @Override
- public void onOpen(WsOutbound outbound) {
- try {
- System.out.println("Open " + me + " to " + to);
- this.myoutbound = outbound;
- mmiList.put( me , this );
- outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onTextMessage(CharBuffer cb) throws IOException {
- System.out.println("Accept Message : " + cb);
- for ( String mmib : mmiList.keySet() ) {
- if ( !to.equals(mmib) )
- continue;
- try
- {
- CharBuffer buffer = CharBuffer.wrap(cb);
- mmiList.get(mmib).myoutbound.writeTextMessage(buffer);
- mmiList.get(mmib).myoutbound.flush();
- }
- catch (Exception e) {
- continue;
- }
- break;
- }
- }
- @Override
- public void onClose(int status) {
- if( status == 1002 || status == 1000)
- {
- System.out.println("Close " + me + " to " + to);
- mmiList.remove(this);
- }
- }
- @Override
- public void onBinaryMessage(ByteBuffer bb) throws IOException {
- }
- }
- }
接下来编写index.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <script type="text/javascript" src="scripts/swfobject.js"></script>
- <script type="text/javascript" src="scripts/jquery.js"></script>
- <script type="text/javascript" src="scripts/web_socket.js"></script>
- <script type="text/javascript" src="scripts/jquery.WebSocket.js"></script>
- <%
- String message_to = request.getParameter( "message_to" );
- String message_me = request.getParameter( "message_me" );
- request.setAttribute( "message_to" , message_to );
- request.setAttribute( "message_me" , message_me );
- %>
- <script>
- $(function ()
- {
- window.onbeforeunload = onbeforeunload_handler;
- window.onunload = onunload_handler;
- function onbeforeunload_handler(){
- //ws.close();
- return warning;
- }
- function onunload_handler()
- {
- //alert(1);
- ws = null;
- }
- });
- var message_to = "${message_to}";
- var message_me = "${message_me}";
- //var ws = new WebSocket("ws://192.168.202.56:8080/websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me);
- var url = "websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me;
- var ws = new $.websocket({
- protocol : "websocket_msg/serverSocket?message_to="+message_to+"&message_me="+message_me,
- domain : "192.168.1.120",
- port : "8080",
- onOpen:function(event){
- showMessage("已成功登录");
- },
- onError:function(event){
- alert("error:"+ event)
- },
- onMessage:function(result){
- receiveMessage(result);
- },
- onClose:function(event){
- ws = null;
- }
- });
- function send(){
- if(!ws){
- alert("已经断开聊天室");
- return;
- }
- var msg=$.trim($("#msg").val());
- if(msg==""){return;}
- ws.send(msg);
- $("#messageInput").val("").focus();;
- }
- function receiveMessage(result){
- showMessage(result);
- }
- function showMessage(msg){
- document.getElementById("chatlog").textContent += msg + "\n";
- }
- </script>
- </head>
- <body>
- <body>
- <textarea id="chatlog" readonly style="width:500px;height:500px;"></textarea><br/>
- <input id="msg" type="text" />
- <button type="submit" id="sendButton" onClick="send()">Send!</button>
- <button type="submit" id="sendButton" onClick="closeConnect()">End</button>
- </body>
- </body>
- </html>
编写完成后,访问index.jsp时需要URL给出两个参数。一个代表发送者,一个代表接收者。
- 例如 ?message_to=1&message_me=2"