websocket收集封装版

具体的配置在之前的一个博客有描述很详细:https://blog.csdn.net/zhaoxichen_10/article/details/84860560
这里是开发过程封装后,记录一下方便后面直接拿来使用。
干货:

1.依赖

<!--websocket-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @Author: Galen
 * @Date: 2019/6/26-14:16
 * @Description: websocket配置类
 **/
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

3.实现
PgsWebSocket:主要工作类

import com.apl.pgs.utils.WebSocketUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint(value = "/websocket")
@Component
public class PgsWebSocket {

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * @Author: Galen
     * @Description: 连接建立成功调用的方法
     * @Date: 2019/6/26-14:48
     * @Param: [session]
     * @return: void
     **/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        WebSocketUtil.addSocket(this);  //加入到set中
        log.info("有新连接{}加入!当前{}人在线", session.getId(), WebSocketUtil.getOnlineCount());
        try {
            sendMessage("欢迎加入!当前在线人数为" + WebSocketUtil.getOnlineCount());
        } catch (IOException e) {
            log.info("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        WebSocketUtil.removeSocket(this);  //从set中删除
        log.info("有一连接关闭!当前还有{}人在线", WebSocketUtil.getOnlineCount());
    }

    /**
     * @Author: Galen
     * @Description: 收到客户端消息后调用的方法
     * @Date: 2019/6/26-14:35
     * @Param: [message, sessionCurrent]
     * @return: void
     **/
    @OnMessage
    public void onMessage(String message, Session sessionCurrent) {
        log.info("来自客户端{}的消息:{}", sessionCurrent.getId(), message);
        /**
         * 向客户端群发消息
         */
        for (PgsWebSocket item : WebSocketUtil.getWebSocketSet()) {
            try {
                //向发件人单独回应
                if (item.session.getId().equals(sessionCurrent.getId())) {
                    item.sendMessage("我是服务器,我已经收到你的信息---" + message);
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Author: Galen
     * @Description: 发生错误时调用
     * @Date: 2019/6/26-14:35
     * @Param: [session, error]
     * @return: void
     **/
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("关闭{}发生错误", session.getId());
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

}

WebSocketUtil :存储,记录,辅助

import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: Galen
 * @Description: webSocket工具类
 * @Date: 2019/6/26-15:31
 * @Param:
 * @return:
 **/
public class WebSocketUtil {

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
    private static CopyOnWriteArraySet<PgsWebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    //获取所有WebSocket对象
    public static CopyOnWriteArraySet<PgsWebSocket> getWebSocketSet() {
        return webSocketSet;
    }

    //添加一个WebSocket对象
    public static void addSocket(PgsWebSocket pgsWebSocket) {
        webSocketSet.add(pgsWebSocket);
        addOnlineCount();//在线数加1
    }

    //移除一个WebSocket对象
    public static void removeSocket(PgsWebSocket pgsWebSocket) {
        webSocketSet.remove(pgsWebSocket);
        subOnlineCount();//在线数减1
    }

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

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

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

4.封装
面向接口编程

接口

public interface SendWebSocket {

    /**
     * @Author: Galen
     * @Description: 群发自定义消息, 向当前所有在线的用户发信息
     * @Date: 2019/6/26-14:56
     * @Param: [message]
     * @return: void
     **/
    void sendGroupInfo(String message);
}

实现类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SendWebSocketImpl implements SendWebSocket {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    public void sendGroupInfo(String message) {
        log.info("当前{}人在线", WebSocketUtil.getOnlineCount());
        for (PgsWebSocket item : WebSocketUtil.getWebSocketSet()) {
            try {
                item.sendMessage("我是pgs服务器,广播信息:" + message);
            } catch (IOException e) {
                continue;
            }
        }
    }
}

5.服务端使用

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(value = "消息", tags = {"消息管理"})
@RestController
@RequestMapping("sys/message")
public class MessageController {

    @Autowired
    private SendWebSocket sendWebSocket;

    @ApiOperation("向客户群发消息")
    @PostMapping("webSocket")
    public void massSending(String msg) {
        sendWebSocket.sendGroupInfo(msg);
    }
}

6.客户端(前端)使用

<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text"/>
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        //根据自己的服务器端口修改
        websocket = new WebSocket("ws://localhost:8082/pgs/websocket");
    } else {
        alert('Not support websocket')
    }

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

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        setMessageInnerHTML("open");
    }

    //接收到消息的回调方法
    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>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值