(二) WebSocket客户端/服务端代码

服务端

服务端我们采用SpringBoot方式集成WebSocket。关键代码如下:

开启WebSocket功能:

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

如果不配置该类,无法将HTTP请求转换为WebSocket请求。

WebSocket服务端代码:

@ServerEndpoint("/imserver/{userId}")
@Component
public class WebSocketServer {
    static Log log= LogFactory.getLog(WebSocketServer.class);
    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap
            <String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:"+userId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
        if(true){
            try {
                //解析发送的报文

                //追加发送人(防止串改)

                String toUserId=this.userId;
                //传送给对应toUserId用户的websocket
                if(webSocketMap.containsKey(toUserId)){
                    if("123".equals(message)){
                        while (true){
                            webSocketMap.get(toUserId).sendMessage("ceshi  text");
                        }
                    }
                    webSocketMap.get(toUserId).sendMessage(message);
                }else{
                    log.error("请求的userId:"+toUserId+"不在该服务器上");
                    //否则不在这个服务器上,发送到mysql或者redis
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:"+userId+",报文:"+message);
        if(webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户"+userId+",不在线!");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}

@ServerEndpoint注解: 类似于Servlet中的RequestMapping

@OnOpen注解: 客户端连接成功时,调用该注解的方法。
@OnClose注解:连接关闭时调用。
@OnMessage注解:收到客户端消息后调用的方法。
@OnError注解:发生错误时的回调函数。

由此可以体会到,WebSocket就是通过HTTP请求建立了长连接。建立连接后,就可以实现客户端与服务端的双向通信了。

客户端

我们用js和java来实现客户端的代码。
js客户端:

<body>
server地址 :  <input id ="serveraddress" type="text" /><br/>
您的用户id :  <input id ="userId" type="text" /><br/>
<button onclick="initSocket()">连接</button><br/>

=====================================================<br/>
消息 :  <input id ="message" type="text" /><br/>
<button onclick="send()">发送</button><br/>
=====================================================<br/>
连接状态 : <button onclick="clearConnectStatu()">清空</button><br/>
<div id="connectStatu"></div><br/>

=====================================================<br/>
收到消息 :<br/>
<div id="receivedMessage"></div><br/>
=====================================================<br/>
心跳 :<br/>
<div id="heartdiv"></div><br/>

</body>

<script src="./jquery.min.js"></script>
<script type="text/javascript">
    var heartflag = false;
    var webSocket = null;
    var tryTime = 0;
    $(function () {

//        initSocket();
        window.onbeforeunload = function () {

        };
    });

    /**
     * 初始化websocket,建立连接
     */
    function initSocket() {
        var serveraddress = $("#serveraddress").val();
        var userId = $("#userId").val();

        if (!window.WebSocket) {
            $("#connectStatu").append(getNowFormatDate()+"  您的浏览器不支持ws<br/>");
            return false;
        }

        webSocket = new WebSocket(serveraddress+"/"+userId);

        // 收到服务端消息
        webSocket.onmessage = function (msg) {
            if(msg.data == "&"){

            }else{
                $("#receivedMessage").append(getNowFormatDate()+"  收到消息 : "+msg.data+"<br/>");
            }
        };

        // 异常
        webSocket.onerror = function (event) {
            heartflag = false;
            $("#connectStatu").append(getNowFormatDate()+"  异常<br/>");
        };

        // 建立连接
        webSocket.onopen = function (event) {
            heartflag = true;
            heart();
            $("#connectStatu").append(getNowFormatDate()+"  建立连接成功<br/>");
            tryTime = 0;
        };

        // 断线重连
        webSocket.onclose = function () {
            heartflag = false;
            // 重试10次,每次之间间隔10秒
            if (tryTime < 10) {
                setTimeout(function () {
                    webSocket = null;
                    tryTime++;
                    initSocket();
                    $("#connectStatu").append( getNowFormatDate()+"  第"+tryTime+"次重连<br/>");
                }, 3*1000);
            } else {
                alert("重连失败.");
            }
        };

    }

    function send(){
        var message = $("#message").val();
        webSocket.send(message);
    }

    function clearConnectStatu(){
        $("#connectStatu").empty();
    }

    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    }

    function heart() {
        if (heartflag){
            webSocket.send("&");
            $("#heartdiv").append(getNowFormatDate()+"  心跳 <br/>");
        }
        setTimeout("heart()", 10*60*1000);

    }
</script>

客户端也有onopen(建立连接)、onclose(关闭连接)、onmessage(接收到服务端消息)、onerror(异常)几个事件。与服务端相对应。

这里我们看重连机制的实现,就是在onclose方法中,重新调用initWebSocket方法,新建一个WebSocket连接。

心跳机制的实现,就是往服务端发送一个约定好的信息,如PING。然后服务端再返回客户端一个约定好的信息,如PONG。定时发送即可。

java客户端

@Component
public class WebSocketClient implements CommandLineRunner, WebSocketHandler {
//项目启动,建立WebSocket连接
    @Override
    public void run(String... args) throws Exception {
        WsWebSocketContainer wsWebSocketContainer = new WsWebSocketContainer();
        wsWebSocketContainer.setDefaultMaxBinaryMessageBufferSize(5120000);
        wsWebSocketContainer.setDefaultMaxTextMessageBufferSize(5120000);
        StandardWebSocketClient client = new StandardWebSocketClient(wsWebSocketContainer);
        WebSocketHandler webSocketHandler=this;
        String uriTemplate = "ws://localhost:8080/imserver/123";
        Object uriVars = null;
        ListenableFuture<WebSocketSession> future =client.doHandshake(webSocketHandler, uriTemplate, uriVars);
        try {
            WebSocketSession session = future.get();
            System.out.println(session);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

//建立连接后,执行的回调函数
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        String str8="123";
        TextMessage message8=new TextMessage(str8.getBytes());
        webSocketSession.sendMessage(message8);
    }
    int count=0;
    //解析服务端发送的消息
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
      count++;
      String msg=  webSocketMessage.getPayload().toString();
      Thread thread=new Thread(new Runnable() {
          @Override
          public void run() {
              System.out.println(Thread.currentThread().getName()+" client receive message:"+msg+"   "+count);
              if(count%5==0){
                  try {
                      Thread.sleep(2000);
                  }catch (Exception e){}
              }
          }
      });
      thread.start();
    }

//异常回调函数
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

    }

//连接关闭后回调函数,重连机制可以在这里实现
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

项目代码已上传至资料中,可在资源中下载。

WebSocket消息保障

WebSocket没有消息保障机制,需要我们自己完成。比如,客户端发送消息后,服务端返回给客户端发送成功的消息。同理,服务端发送消息后,客户端发送收到消息的ack。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码的小小酥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值