webSocket的简单使用(2)

该文章展示了如何在SpringBoot应用中配置WebSocket服务,包括添加相关依赖、设置服务器节点,以及编写后端处理方法如连接打开、关闭、消息处理等。同时,文章提供了前端JavaScript代码片段,说明了如何在浏览器端创建WebSocket连接并接收服务器消息。
摘要由CSDN通过智能技术生成

1.依赖

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

2.服务器节点

如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理

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

3.简单代码后端代码示例

package com.lg.jzw.rtsp.rtsp;

import com.lg.jzw.rtsp.entity.ImageEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;


//@ServerEndpoint(value = "/webSocketService", encoders = {ImageEncoder.class})
@ServerEndpoint("/webSocketService")
@Component
@Slf4j
@Service
public class WebSocketServer {

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

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.session = session;
        this.userId = session.getId();
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
            //加入set中
        } else {
            webSocketMap.put(userId, this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        HashMap<String, String> data = new HashMap<>();
        data.put("userId", userId);
//        sendMessageByStr(JSON.toJSONString(AjaxResult.success("连接成功", data)));
    }


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

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息,必须是json串
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + userId + ",报文:" + message);
        if (StringUtils.isNotBlank(message)) {
            MediaTransfer mediaTransfer = new MediaTransfer();
            mediaTransfer.live(message, userId);
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        log.error("websocket error: ", error);
        onClose();
    }

    public void sendMessageByStr(String message) {
        if (StringUtils.isNotBlank(message)) {
            try {
                if (this.session.isOpen()) {
                    this.session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                log.error("发送到用户:" + this.userId + "信息失败 ,信息是:" + message);
                log.error("websocket send str msg exception: ", e);
            }
        }
    }

    public void sendMessageByObject(Object message) throws IOException, EncodeException {
        if (message != null) {
            this.session.getBasicRemote().sendObject(message);
        }
    }

    public void sendBinary(ByteBuffer message) {
        if (message != null) {
            try {
                this.session.getBasicRemote().sendBinary(message);
            } catch (IOException e) {
                log.error("发送到用户:" + this.userId + "信息失败 ,信息是:" + message);
                log.error("websocket send byteBuffer msg exception: ", e);
            }
        }
    }

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

    /**
     * 向所有的客户端发送消息
     *
     * @param byteBuffer byteBuffer
     * @throws IOException IOException
     */
    public static void sendAllByBinary(ByteBuffer byteBuffer) {
        if (!webSocketMap.isEmpty()) {
            Collection<WebSocketServer> values = webSocketMap.values();
            for (WebSocketServer next : values) {
                next.sendBinary(byteBuffer);
            }
        }
    }

    public void sendAllByObject(Object message) throws IOException, EncodeException {
        if (!webSocketMap.isEmpty()) {
            Collection<WebSocketServer> values = webSocketMap.values();
            for (WebSocketServer next : values) {
//                next.sendMessageByObject(message);
//                next.session.getBasicRemote().sendText();
                if (this.session == next.session) {
                    next.sendMessageByObject(message);
                }
            }
        }
    }

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

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

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

}

4.前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var websocket = null;
    if ('WebSocket' in window) {
        websocket = new WebSocket('ws://127.0.0.1:8989/webSocket');
    } else {
        alert('该浏览器不支持websocket!');
    }

    websocket.onopen = function (event) {
        console.log('建立连接');
    }

    websocket.onclose = function (event) {
        console.log('连接关闭');
    }

    websocket.onmessage = function (event) {
        console.log('收到消息:' + event.data)

        //所要执行的操作
    }

    websocket.onerror = function () {
        alert('websocket通信发生错误!');
    }

    window.onbeforeunload = function () {
        websocket.close();
    }

</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Vue 2中使用WebSocket,你可以按照以下步骤进行操作: 1. 首先,确保你已经在项目中安装了WebSocket的库。你可以使用`npm`或`yarn`来安装`vue-native-websocket`或`vue-socket.io`等WebSocket库。 2. 在你的Vue组件中,你需要引入WebSocket库。例如,如果你使用的是`vue-native-websocket`,可以在组件中添加以下代码: ```javascript import VueNativeSock from 'vue-native-websocket'; Vue.use(VueNativeSock, 'ws://localhost:8080', { format: 'json', reconnection: true, }); ``` 这将使你能够在Vue组件中使用WebSocket功能。 3. 在Vue组件中,你可以使用以下方法来连接和处理WebSocket: ```javascript export default { data() { return { socket: { isConnected: false, message: '', reconnectError: false, }, }; }, created() { // 监听WebSocket连接成功事件 this.$options.sockets.onopen = () => { this.socket.isConnected = true; }; // 监听WebSocket接收到消息事件 this.$options.sockets.onmessage = (event) => { this.socket.message = event.data; }; // 监听WebSocket连接关闭事件 this.$options.sockets.onclose = () => { this.socket.isConnected = false; }; // 监听WebSocket连接错误事件 this.$options.sockets.onerror = () => { this.socket.reconnectError = true; }; }, }; ``` 在上述代码中,我们将WebSocket连接和接收消息的逻辑放在了Vue组件的`created`生命周期钩子中。 4. 现在,你可以在Vue组件中使用`socket`对象来发送和接收消息。例如,你可以使用以下方法来发送消息: ```javascript this.$socket.send('Hello, WebSocket!'); ``` 你也可以在模板中使用`socket`对象的属性来显示接收到的消息: ```html <div>{{ socket.message }}</div> ``` 这是一个简单使用WebSocket的例子。你也可以根据你的需求进一步使用WebSocket的功能,比如发送和接收JSON格式的数据等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

研程序笔记

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

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

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

打赏作者

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

抵扣说明:

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

余额充值