WebSocket长连接

博客地址:
http://www.cnblogs.com/best/archive/2016/09/12/5695570.html
客户端测试代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>WebSocket客户端</title>
    </head>
    <body>
        <div>
            <input type="button" id="btnConnection" value="连接" />
            <input type="button" id="btnClose" value="关闭" />
            <input type="button" id="btnSend" value="发送" />
        </div>
        <script type="text/javascript" src="js/jquery-2.0.3.min.js" ></script>
        <script>
            var socket;
            (function(){
                    if (typeof(WebSocket) == 'undefined') {
                        alert("您的浏览器不支持WebSocket");
                    return;
                }
            })();

            $('#btnConnection').click(function(){
                //实例化WebSocket对象,指定要连接的服务器地址与端口
                socket = new WebSocket("ws://127.0.0.1:8080/WebSocket/ws/zhangsan");
                //打开事件
                socket.onopen = function(){
                    alert("Socket 已打开");
                    //socket.send("这是来自客户端的消息"+location.href+new Date());
                };
                //获得消息事件
                socket.onmessage = function(msg){
                    alert(msg.data);
                };
                //关闭事件
                socket.onclose = function(){
                    alert("Socket 已关闭");
                };
                //发生了错误事件
                socket.onerror = function(){
                    alert("发生了错误");
                }
            });

            //发送消息
            $('#btnSend').click(function(){
                socket.send("这是来自客户端的消息:"+location.href+new Date());
            });

            //关闭
            $('#btnClose').click(function(){
                socket.close();
            });
        </script>
    </body>
</html>

服务器端测试代码:

package com.webSocket;

import javax.websocket.CloseReason;
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;

@ServerEndpoint("/ws/{user}")
public class WSServer {

    private String currentUser;

    @OnOpen
    public void onOpen(@PathParam("user")String user,Session session) {
        currentUser = user;
        System.out.println("connected ...." + session.getId());
    }

    @OnMessage
    public String onMessage(String message,Session session) {
        System.out.println(currentUser + ":" +message);
        return currentUser + ":" + message;
    }

    @OnClose
    public void onClose(Session session,CloseReason closeReason) {
        System.out.println(String.format("Session %s closed because of %s", session.getId(),closeReason));
    }

    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }

}

猜你喜欢

转载自blog.csdn.net/fangdengfu123/article/details/78183303