WebSocket是一种在单个TCP连接上进行全双工通讯的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
WebSocket长连接减少了连接的开销,建立连接之后只关心数据本身。
开发、测试工具:IntelliJ IDEA、VSCODE、Visual Studio Code、Flutter
外网映射工具:路由侠
- 使用IDEA创建一个WebScoket项目
-
选择Spring Initializr 然后点击Next;
image.png
-
修改好名字然后直接点击Next,选项默认即可
image.png
-
Developer Tools 选择 Spring Boot DevTools、Web 选择 Spring Web、TemPlate Engines 选择 Thymeleaf,点击Next
image.png
-
选择好项目保存目录然后点击Finish
image.png
- 在pom.xml中添加websocket依赖
-
选择Spring Initializr 然后点击Next;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

- 在WebsocketApplication (启动类)中添加bean,如果报错,需要检查依赖是否配置正确,一般都为依赖没有正常下载
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

- 添加websocket server类
package com.example.demo.websocket;
import org.springframework.stereotype.Component;
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;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Auther: shigc
* @Date: 2018/12/15 11:53
* @Description: websocket
*/
@ServerEndpoint("/websocket/{pageCode}")
@Component
public class WebSocket {
private static final String loggerName = WebSocket.class.getName();
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
public static Map<String, List<Session>> electricSocketMap = new ConcurrentHashMap<String, List<Session>>();
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam("pageCode") String pageCode, Session session) throws IOException {
List<Session> sessions = electricSocketMap.get(pageCode);
if (null == sessions) {
List<Session> sessionList = new ArrayList<>();
sessionList.add(session);
electricSocketMap.put(pageCode, sessionList);
} else {
sessions.add(session);
}
System.out.println("连接成功:");
session.getBasicRemote().sendText("连接成功:告知连接方");
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam("pageCode") String pageCode, Session session) {
if (electricSocketMap.containsKey(pageCode)) {
electricSocketMap.get(pageCode).remove(session);
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("websocket received message:" + message);
try {
session.getBasicRemote().sendText("这是推送测试数据!您刚发送的消息是:" + message);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
;
}
}

- 添加测试界面
<head>
<meta charset="UTF-8"></meta>
<title>springboot项目WebSocket测试demo</title>
</head>
<body>
<h3>springboot项目websocket测试demo</h3>
<h4>测试说明</h4>
<h5>文本框中数据数据,点击‘发送测试’,文本框中的数据会发送到后台websocket,后台接受到之后,会再推送数据到前端,展示在下方;点击关闭连接,可以关闭该websocket;可以跟踪代码,了解具体的流程;代码上有详细注解</h5>
<br />
<input id="text" type="text" />
<button onclick="send()">发送测试</button>
<hr />
<button onclick="clos()">关闭连接</button>
<hr />
<div id="message"></div>
<script>
var websocket = null;
if('WebSocket' in window){
websocket = new WebSocket("ws://127.0.0.1:8080/websocket/0");
// websocket = new WebSocket('ws://localhost:8080/ws/foo')
}else{
alert("您的浏览器不支持websocket");
}
websocket.onerror = function(){
setMessageInHtml("send error!");
}
websocket.onopen = function(){
setMessageInHtml("connection success!")
}
websocket.onmessage = function(event){
setMessageInHtml(event.data);
}
websocket.onclose = function(){
setMessageInHtml("closed websocket!")
}
window.onbeforeunload = function(){
clos();
}
function setMessageInHtml(message){
document.getElementById('message').innerHTML += message;
}
function clos(){
websocket.close(3000,"强制关闭");
}
function send(){
var msg = document.getElementById('text').value;
websocket.send(msg);
}
</script>
</body>
</html>

以上,项目所必须的配置以及代码已经全部编写完毕。
- 项目内调试:执行Run,编译项目,编译成功之后可以在浏览器器中打开http://localhost:8080/testHtml.html
image.png
表示已经连接成功
消息互发
- Html(Vue)项目调试:建立一个Vue项目用来进行调试
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<div @click="send">发送数据</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
msg: 'Welcome to Your Vue.js App',
path:"ws://127.0.0.1:8080/websocket/page",
// 'path': "ws://lxh1991.e2.luyouxia.net:26748//websocket/0",
socket:""
}
},
mounted() {
this.init()
},
methods: {
init: function () {
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
// 实例化socket
this.socket = new WebSocket(this.path)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
}
},
open: function () {
console.log("socket连接成功")
},
error: function () {
console.log("连接错误")
},
getMessage: function (msg) {
console.log(msg.data)
},
send: function () {
this.socket.send('发送数据给服务端')
},
close: function () {
console.log("socket已经关闭")
},
},
}
</script>


- Flutter模拟器连接(因为涉及模拟器的一些问题,Android操作系统中,将本地电脑映射为10.0.2.2,但是我用10.0.2.2一样不行)所以此处使用路由侠进行映射,直接使用外网链接进行socket连接,此处使用web_socket_channel来进行webSocket连接
image.png IDEA代码
网友评论