目录
- 1.pom依赖坐标
- 2.项目配置端口和项目包名
- 2.创建处理器
- 3.注册处理器
- 4.前端页面
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);//和客户端建立连接@Overridepublic void afterConnectionEstablished(WebSocketSession session) {log.info("和客户端建立连接"+session.getId());//初始建立连接业务逻辑处理。。。。。。。。。。。。 }//和客户端断开连接@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {log.info("和客户端断开连接");//断开连接业务逻辑处理。。。。。。。。。。。。super.afterConnectionClosed(session, status); }// 获取客户端发来的消息并响应消息@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {String receObjStr = message.getPayload();log.info("sessionID==="+session.getId());//接收客户端消息进行业务逻辑处理。。。。。。。。。。。。 // 发送消息给客户端session.sendMessage(new TextMessage("字符串"));}//异常处理@Overridepublic void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {session.close(CloseStatus.SERVER_ERROR);log.error("连接异常", exception);}
}
3.注册处理器
@Configuration
@EnableWebSocket
public class WebSocketServerConfigure implements WebSocketConfigurer {@Autowiredprivate WebSocketHandler webSocketHandler;@Overridepublic 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>