websocket(一)--握手

最近在琢磨怎么实现服务端的消息推送,因为以前都是通过客户端请求来获取信息的,如果需要实时信息就得轮询,比如通过ajax不停的请求。
websocket相当于对HTTP协议进行了升级,客户端和服务端通过websocket协议握手成功后,两者之间建立一个数据通道(长连接,双通道),以此来传输数据,而不必每次都由客户端发起请求。
这篇文章先来通过代码来介绍怎样实现“握手”,消息推送在后边的文章中写。
注意:1.JavaEE版本为7.0  
     2.tomcat版本为8.0
     3.不需要额外导入其他的jar包
  由于websocket不支持低版本的javaEE和tomcat,所以必须符合上述条件,我是在Myeclipse2014 的IDE中进行编码的,该IDE支持javaEE7.0

WebSocketServer .java

package socket;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/socket")  
public class WebSocketServer {
    @OnMessage  
    public void onMessage(String message, Session session)   
        throws IOException, InterruptedException {  
        //输出客户端发来的信息
        System.out.println("Received: " + message);  

        // 向客户端发送信息  
        session.getBasicRemote().sendText("This is message from server");  
    }  

    @OnOpen  
    public void onOpen () {  
        System.out.println("Client connected");  
    }  

    @OnClose  
    public void onClose () {  
        System.out.println("Connection closed");  
    }  



}

使用@ServerEndpoint注解后该类就类似一个servlet了。包含的方法如上。这部分代码即服务端代码。

下面的客户端代码:
socketClient.html




Testing websockets

<div id="messages"></div>
<script type="text/javascript">
    /*   申请一个WebSocket对象,参数是需要连接的服务器端的地址 */
    var webSocket =  new WebSocket('ws://localhost:8080/websockettest/socket');

    /* 如果出现连接,处理,接收,发送数据失败的时候就会触发onerror事件 */
    webSocket.onerror = function(event) {
        onError(event)
    };

    /* 当websocket创建成功时,即会触发onopen事件 */
    webSocket.onopen = function(event) {
        onOpen(event)
    };

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

    /* 当客户端收到服务端发送的关闭连接的请求时,触发onclose事件 */
    webSocket.onclose = function(event) {
        onMessage(event)
    };

    function onMessage(event) {
        alert("message:"+event.data);
    }

    function onOpen(event) {
        alert("open success");
        webSocket.send('hello');
    }

    function onClose(event) {
        alert("closed");
    }

    function onError(event) {
        alert("error");
    }

</script>



以上就是实现客户端与服务端握手的实例。

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/dingxiaoyue/p/4931742.html