WebSockt

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="application/javascript">
    $(function () {
        initSocket();
    })
    var socket;

    //登录过后初始化socket连接
    function initSocket(userId) {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket/websocket");
        }
        //socket连接地址: 注意是ws协议
        socket = new WebSocket("ws://localhost:8080/websocket/"+userId);
        socket.onopen = function () {
            console.log("Socket 已打开");
        };
        //获得消息事件
        socket.onmessage = function (msg) {
            var histroy = $("#history").val();
            $("#history").val(histroy + "\r\n" + msg.data);
            console.log($(msg));
        };
        //关闭事件
        socket.onclose = function () {
            console.log("Socket已关闭");
        };
        //错误事件
        socket.onerror = function () {
            alert("Socket发生了错误");
        };
        $(window).on("unload", function () {
            socket.close();
        });
    }

    //点击按钮发送消息
    function send() {
        console.log("发送消息: " + $("#msg").val());
        socket.send($("#msg").val());
    }

</script>
</html>
package com.JYT.service.motor.imp;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//https://www.jianshu.com/p/a21e11b19c83
@ServerEndpoint("/motor/mowebsocket")
@Component
@Service
public class WebSocketServer {

    private Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //创建一个线程安全的map
    private static List<WebSocketServer> users = new ArrayList<>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //放入map中的key,用来表示该连接对象
    private String username;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String username) {
        this.session = session;
        this.username = username;
        users.add(this);
        //users.put(username, this);   //加入map中,为了测试方便使用username做key
        addOnlineCount();           //在线数加1
        logger.info(username + "加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        users.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        logger.info("一个连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后触发的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        logger.info("来自客户端的消息:" + message);
        //群发消息
        try {
            if (StringUtils.isEmpty(message)) {
                return;
            }
            sendInfo(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发生错误 session: " + session);
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     */
    public void sendInfo(String message) throws IOException {
        for (WebSocketServer item : users) {
            try {
                item.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

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

 

posted @ 2020-05-13 10:05  迸发图强  阅读(172)  评论(0编辑  收藏  举报