什么是Socket
在计算机通信领域,socket 被翻译为“套接字”,它是计算机之间进行通信的一种约定或一种方式。通过 socket 这种约定,一台计算机可以接收其他计算机的数据,也可以向其他计算机发送数据
Socket起源
socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,都可以用“打开open –> 读写write/read –> 关闭close”模式来操作。
Socket的主要作用
主要是用来解决网络通信的
本篇重点
Socket先了解这么多,更深的内容可以自行补充。本篇文章主要想实现 平台在线人数实时统计的功能
前后端
- 后端:SpringBoot+Socket
- 前端:Vue
具体步骤
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
socket配置
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer端
**
* 由于是websocket 所以原本是@RestController的http形式
* 直接替换成@ServerEndpoint即可,作用是一样的 就是指定一个地址
* 表示定义一个websocket的Server端
*/
@Component
@ServerEndpoint("/websocket/{userId}")
public class MySocket {
private Session session;
private static CopyOnWriteArraySet<MySocket> webSockets = new CopyOnWriteArraySet<>();
private static Map<String, Session> sessionPool = new HashMap<String, Session>();
/**
* 有新的连接加入
**/
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId") String userId) {
this.session = session;
webSockets.add(this);
sessionPool.put(shopId, session);
// 新的连接加入 通知客户端
sendMessageToAll(webSockets.size() + "");
System.out.println("【websocket消息】有新的连接,总数为:" + webSockets.size());
}
/**
* websocket消息连接断开
**/
@OnClose
public void onClose() {
webSockets.remove(this);
// 断开连接 通知客户端
sendMessageToAll(webSockets.size() + "");
System.out.println("【websocket消息】连接断开,总数为:" + webSockets.size());
}
/**
* websocket消息收到客户端消息
**/
@OnMessage
public void onMessage(String message) {
System.out.println("websocket消息收到客户端消息:" + message);
}
/**
* 通知所有的客户端
*
* @param message
*/
public void sendMessageToAll(String message) {
for (MySocket webSocket : webSockets) {
System.out.println("【websocket】通知所有的客户端:" + message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Vue代码
export default {
created() {
// 页面创建 生命周期函数
this.initWebSocket()
},
destroyed: function () {
// 页面销毁生命周期函数
this.websocketclose();
},
methods: {
initWebSocket: function () {
// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
this.websock = new WebSocket("ws://localhost:8080/websocket/userId");
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
},
websocketonopen: function () {
console.log("WebSocket连接成功...");
},
websocketonerror: function (e) {
console.log("WebSocket连接发生错误...");
},
websocketonmessage: function (e) {
console.log(e.data);
if (e.data !== undefined) {
this.onlineUser = e.data
}
},
websocketclose: function (e) {
console.log("connection closed (" + e.code + ")");
}
}
拦截器设置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/websocket/**"").permitAll()
.anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
- 测试-项目启动后台
- 测试-启动前台-效果
测试-查看后台日志打印及界面
测试-打开第二个浏览器后查看后台日志打印
测试-关闭一个浏览器后查看
小结
本篇主要以一个小case介绍了socket的用法,希望能对初接触
的小伙伴有些借鉴。要彻底搞懂Socket还要进一步深入
最近听到一句话,很有感触,送给大家 “基础不牢,地动山摇”!小伙伴们一起加油!