WebSocket入门

没事研究了下,WebSocket.

WebSocket是用来双向握手的,和Http的不同就是http只能由客户端向服务器发送消息,而webSocket可以双向发请求,webSocket用来做轮询最好。我们公司就是用webSocket来由后端向前段发起播放命令。

首先前端,代码。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
websocket Demo---- user <br />
<input id="text" type="text" />
<button onclick="send()"> Send </button>
<button   onclick="closeWebSocket()"> Close </button>
<div id="message">   </div>

<script type="text/javascript">
    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8088/Exeirse2/websocketTest/user");
        console.log("link success")
    }else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }
    console.log("-----")
    //接收到消息的回调方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>

</body>
</html>

后端代码,以及jar包,我用的javaee-api-7.0.jar,用了这个包,下面的注解才不会报错。

package cn.itcast.utils;


import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @Class: WebSocket
 * @Description: 简单websocket demo
 *
 */
@ServerEndpoint(value="/websocketTest/{userId}")
public class WebSockets {
    private Logger logger = LoggerFactory.getLogger(WebSockets.class);

    private static String userId;

    //连接时执行
    @OnOpen
    public void onOpen(@PathParam("userId") String userId,Session session) throws IOException{
        this.userId = userId;
        System.out.println("链接成功");
        logger.debug("新连接:{}",userId);
}

    //关闭时执行
    @OnClose
    public void onClose(){
        logger.debug("连接:{} 关闭",this.userId);
    }

    //收到消息时执行
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        logger.debug("收到用户{}的消息{}",this.userId,message);
        System.out.println("收到用户{}的消息{}");
        session.getBasicRemote().sendText("收到 "+this.userId+" 的消息 "); //回复用户
    }

    //连接错误时执行
    @OnError
    public void onError(Session session, Throwable error){
        logger.debug("用户id为:{}的连接发送错误",this.userId);
        System.out.println("用户id为:{}的连接发送错误");
        error.printStackTrace();
    }

}

访问就行。当时我抱错

NoClassDefFoundError这个,后来是将这个里面的org.apache.cxf.jaxws22.spi.ProviderImpl值改为这个com.sun.xml.internal.ws.spi.ProviderImpl


同样的将它修改,就不报错了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章