websocket

http://haoningabc.iteye.com/blog/2169054 web介绍 web介绍
一、客户端
1.var ws = new WebSocket(“ws://localhost:8080”);
申请一个WebSocket对象,参数是需要连接的服务器端的地址,同http协议使用http://开头一样,WebSocket协议的URL使用ws://开头,另外安全的WebSocket协议使用wss://开头。
ws.send(“hello”);
用于叫消息发送到服务端

2.ws.onopen = function() { console.log(“open”)};
当websocket创建成功时,即会触发onopen事件

3.ws.onmessage = function(evt) { console.log(evt.data) };
当客户端收到服务端发来的消息时,会触发onmessage事件,参数evt.data中包含server传输过来的数据

4.ws.onclose = function(evt) { console.log(“WebSocketClosed!”); };
当客户端收到服务端发送的关闭连接的请求时,触发onclose事件

5.ws.onerror = function(evt) { console.log(“WebSocketError!”); };
如果出现连接,处理,接收,发送数据失败的时候就会触发onerror事件


二、服务端
第一个用于处理websocket请求
第一个类
public class SocketServer extends WebSocketServlet {
    private static final long serialVersionUID = 1L;
    //……
    @Override
    protected StreamInbound createWebSocketInbound(String arg0,
            HttpServletRequest arg1) {
        // TODO Auto-generated method stub
        return new ChatWebSocket(users);
    }
}

这个Servlet继承自WebSocketServlet,实现createWebSocketInbound方法。该方法返回第二个类的实例。

第二个用于处理每一次具体的WebSocket任务
protected void onTextMessage(CharBuffer message) throws IOException { }
文本消息响应
protected void onBinaryMessage(ByteBuffer arg0) throws IOException { }
二进制消息响应
protected void onOpen(WsOutbound outbound) { }
建立连接的触发的事件
protected void onClose(int status) { }
关闭连接时触发的事件



客户端代码
/opt/apache-tomcat-7.0.62/webapps/websocket
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>    
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">    
<title>Insert title here</title>    
</head>
<script type="text/javascript">    
    var ws = null;  
    function log(text) {  
       document.getElementById("log").innerHTML = (new Date).getTime() + ": " + text +"<br>"+  document.getElementById("log").innerHTML;  
    }    
    function startServer() {    
        var url = document.getElementById("serverip").value;// "ws://192.168.0.102:8887";    
        if ('WebSocket' in window) {    
            ws = new WebSocket(url);    
        } else if ('MozWebSocket' in window) {    
            ws = new MozWebSocket(url);    
        } else {    
            alert('浏览器不支持');    
            return;  
        }    
        ws.onopen = function() {    
            alert('Opened!');    
        };    
        // 收到服务器发送的文本消息, event.data表示文本内容    
        ws.onmessage = function(event) {    
            //alert('Receive message: ' + event.data);   
            log('Receive message: ' + event.data);   
        };    
        ws.onclose = function() {    
          alert('Closed!');    
        }    
        document.getElementById("conbtn").disabled="true";  
        document.getElementById("stopbtn").removeAttribute('disabled');  
    }    
    //发送信息    
    function sendMessage(){    
        var textMessage=document.getElementById("textMessage").value;    
            
        if(ws!=null&&textMessage!=""){    
            ws.send(textMessage);    
                
        }    
    }    
    function stopconn(){  
        ws.close();  
        document.getElementById("conbtn").removeAttribute('disabled');  
        document.getElementById("stopbtn").disabled="true";  
    }  
</script>



服务端代码
import java.util.ArrayList;
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 HelloWorldWebSocketServlet extends WebSocketServlet {
    private static ArrayList mmiList  = new ArrayList();

    protected StreamInbound createWebSocketInbound(String subProtocol,
            HttpServletRequest arg1) {
        return new MyMessageInbound();
    }

    private class MyMessageInbound extends MessageInbound {
        WsOutbound myoutbound;

        @Override
        public void onOpen(WsOutbound outbound) {
            try {
                System.out.println("Open Client.");
                this.myoutbound = outbound;
                mmiList .add(this);
                outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onClose(int status) {
            System.out.println("Close Client.");
            mmiList .remove(this);
        }

        @Override
        protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
            // TODO Auto-generated method stub  

        }

        @Override
        protected void onTextMessage(CharBuffer message) throws IOException {
            // TODO Auto-generated method stub  
            System.out.println("onText--->" + message.toString());
            for (int i=0;i< mmiList.size();i++ ) {
                MyMessageInbound mmib = (MyMessageInbound) mmiList.get(i);
                CharBuffer buffer = CharBuffer.wrap(message);
                mmib.myoutbound.writeTextMessage(buffer);
                mmib.myoutbound.flush();
            }

        }
    }
}

web配置
<servlet>
      <servlet-name>hello</servlet-name>
      <servlet-class>com.HelloWorldWebSocketServlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/websocket/test</url-pattern>
    </servlet-mapping>
</web-app>





完整的web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<web-app 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_3_0.xsd"
  version="3.0"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

  <servlet>  
      <servlet-name>hello</servlet-name>  
      <servlet-class>com.HelloWorldWebSocketServlet</servlet-class>  
    </servlet>  
    <servlet-mapping>  
      <servlet-name>hello</servlet-name>  
      <url-pattern>/websocket/test</url-pattern>  
    </servlet-mapping>
</web-app>

你可能感兴趣的:(java,Web,浏览器,servlet)