Websocket服务监听收发消息

1.pom依赖坐标

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

2.项目配置端口和项目包名

application.properties

server.port=8088
//路径规范:为应用的所有servlet提供一个统一的前缀,使URL结构更加清晰和一致
server.servlet.context-path=/rxtxcommon

2.创建处理器

import com.fazecast.jSerialComm.SerialPort;
import com.groupname.rxtxcommon.service.SerialPortService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.List;
import java.util.Map;


@Component
public class WebSocketHandler extends TextWebSocketHandler {

    private static Logger log = LoggerFactory.getLogger(WebSocketHandler.class);
    //和客户端建立连接
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("和客户端建立连接"+session.getId());
	    //初始建立连接业务逻辑处理
		。。。。。。
		。。。。。。  
    }

    //和客户端断开连接
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("和客户端断开连接");
       //断开连接业务逻辑处理
		。。。。。。
		。。。。。。
        super.afterConnectionClosed(session, status);	    
    }

    // 获取客户端发来的消息并响应消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String receObjStr = message.getPayload();
        log.info("sessionID==="+session.getId());
		//接收客户端消息进行业务逻辑处理
		。。。。。。
		。。。。。。        
        // 发送消息给客户端
        session.sendMessage(new TextMessage("字符串"));
    }
	
	//异常处理
	@Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        session.close(CloseStatus.SERVER_ERROR);
        log.error("连接异常", exception);
    }
}

3.注册处理器

@Configuration
@EnableWebSocket
public class WebSocketServerConfigure implements WebSocketConfigurer {

    @Autowired
    private WebSocketHandler webSocketHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    	//前端用websocket建立连接
        registry.addHandler(webSocketHandler, "/websocket");
            //这是另一种方式,但是前端用SockJS建立连接
//        registry.addHandler(webSocketHandler, "/websocket").withSockJS();
    }
}

4.前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
    <script src="https://cdn.bootcss.com/sockjs-client/0.3.4/sockjs.min.js"></script>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<style>
    .jumbotron {
        width: 100%;
    }

    #text {
        height: 3rem;
        font-size: 1rem;
        line-height: 3rem;
        margin: 1rem;
    }

    .btn {
        margin-right: 5px;
    }

    #connect {
        margin-left: 1rem;
    }

    #log {
        margin: 1rem 0 0 1rem;
    }

</style>
<div class="container">
    <div class="row">
        <div class="jumbotron">
            <input type="text" placeholder="请输入你想传输的内容" id="text" class="col-lg-12"/>
            <input type="button" value="连接" class="btn btn-info" id="connect" onclick="connect()"/>
            <input type="button" value="发送" class="btn btn-success" id="sent" disabled="disabled" onclick="sent()"/>
            <input type="button" value="断开" class="btn btn-danger" id="disconnect" disabled="disabled"
                   onclick="disconnect()"/>
            <div id="log">
                <p>聊天记录:</p>
            </div>
            <input type="button" value="" class="btn btn-success" id="openCom" disabled="disabled"
                   onclick="getCommSer()"/>
        </div>
    </div>
</div>
<script type="text/javascript">
    let text = document.querySelector('#text');
    let connectBtn = document.querySelector("#connect");
    let sentBtn = document.querySelector("#sent");
    let disconnectBtn = document.querySelector("#disconnect");
    let logDiv = document.querySelector("#log");
    let ws = null;
    
    function connect(operNum) {
        debugger
        //rxtxcommon是springboot项目的包名
		//application.properties
		//server.port=8088
		//server.servlet.context-path=/rxtxcommon        
		
        ws = new WebSocket("ws://localhost:8088/rxtxcommon/websocket")       
        ws.onopen = function () {
        //如果与后端websocket成功建立连接那么onopen 函数会触发
            setConnected(true);
            log('和服务端连接成功!');
        };
        
        // 监听服务端返回的消息
        ws.onmessage = function(event) {
            console.log("测试接收服务器信息"+event)
            log('收到服务端消息:' + event.data);
        };
    }

    function sent() {
        if (ws != null) {
            ws.send(text.value);
            log('客户端说:' + text.value);
        } else {
            log('请先建立连接!')
        }
    }

    function disconnect() {
        if (ws != null) {
            ws.close();
            ws = null;
        }
        setConnected(false);
    }

    function log(value) {
        let content = document.createElement('p');
        content.innerHTML = value;
        logDiv.appendChild(content);
        text.value = '';
    }

    function setConnected(connected) {
        connectBtn.disabled = connected;
        disconnectBtn.disabled = !connected;
        sentBtn.disabled = !connected;
    }

</script>
</body>
</html>

相关推荐

  1. Websocket服务监听收发消息

    2024-03-17 00:06:02       22 阅读
  2. uniapp websocket 消息队列 例子

    2024-03-17 00:06:02       40 阅读
  3. Springboot-接入WebSocket服务

    2024-03-17 00:06:02       27 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-17 00:06:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-17 00:06:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-17 00:06:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-17 00:06:02       18 阅读

热门阅读

  1. Meson编译工具安装及使用Meson编译DPDK

    2024-03-17 00:06:02       23 阅读
  2. WSL与VirtualBox区别

    2024-03-17 00:06:02       21 阅读
  3. CentOS8安装docker

    2024-03-17 00:06:02       16 阅读
  4. docker部署zabbix使用postgresql数据库

    2024-03-17 00:06:02       19 阅读
  5. C语言演示多线程编程条件下自旋锁和屏障的使用

    2024-03-17 00:06:02       17 阅读
  6. 使用docker搭建Komga

    2024-03-17 00:06:02       20 阅读
  7. Docker 容器和 Kubernetes 退出码 —— 筑梦之路

    2024-03-17 00:06:02       16 阅读
  8. CCF 202009-3 点亮数字人生(拓扑排序)

    2024-03-17 00:06:02       19 阅读
  9. 70后姐妹上海创业,要IPO了

    2024-03-17 00:06:02       20 阅读
  10. AMS、PMS和WMS学习链接

    2024-03-17 00:06:02       16 阅读
  11. 怎么绕过CDN查找真实IP

    2024-03-17 00:06:02       16 阅读
  12. 内网 IP 地址泄漏原理以及修复方法

    2024-03-17 00:06:02       20 阅读
  13. vue单页面应用?

    2024-03-17 00:06:02       16 阅读
  14. 小程序学习4 mock

    2024-03-17 00:06:02       18 阅读