本文共 4462 字,大约阅读时间需要 14 分钟。
360百科:
WebSocket 协议是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信--允许服务器主动发送信息给客户端。在 WebSocket 产生之前,双工通信是通过不停发送HTTP请求,从服务器拉取更新来实现,这导致了效率低下。
在实现websocket连线过程中,需要通过浏览器发出websocket连线请求,然后服务器发出回应,这个过程通常称为"握手" 。在 WebSocket API,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。在此WebSocket 协议中,为我们实现即时服务带来了两大好处:
1. Header
互相沟通的Header是很小的-大概只有 2 Bytes
2. Server Push
服务器的推送,服务器不再被动的接收到浏览器的请求之后才返回数据,而是在有新数据时就主动推送给浏览器。
我们创建一个 SpringBoot 工程,实现用户A发送消息给用户B,B能及时收到。B也能给A发送消息。
代码结构:
pom.xml
4.0.0 com.study study-websocket 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE org.springframework.boot spring-boot-starter-web org.projectlombok lombok org.springframework.boot spring-boot-starter-websocket 2.1.18.RELEASE
配置文件:application.yml
server: port: 80
index.html
SpringBoot 整合 WebSocket 对方ID:消息内容: 对方说:
配置类 WebSocketConfig:
package com.study.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter;/** * @author biandan * @description * @signature 让天下没有难写的代码 * @create 2021-06-21 下午 8:35 */@Configurationpublic class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
核心类处理类 MyWebSocket:
package com.study.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;import javax.websocket.*;import javax.websocket.server.ServerEndpoint;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;/** * @author biandan * @description * @signature 让天下没有难写的代码 * @create 2021-06-21 下午 10:19 */@ServerEndpoint(value = "/send")@Component@Slf4jpublic class MyWebSocket { //在线人数 private static AtomicInteger onlineCount = new AtomicInteger(0); //在线客户端 private static MapclientsMap = new ConcurrentHashMap<>(); //连接建立成功调用的方法 @OnOpen public void onOpen(Session session) { //在线数 +1 onlineCount.incrementAndGet(); clientsMap.put(session.getId(), session); log.info("有新的客户端连接加入,客户ID={},当前总在线人数为:{}", session.getId(), onlineCount.get()); } //接收消息,并回传 @OnMessage public void onMessage(String message, Session session) { log.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message); try { String[] split = message.split(","); String userId = split[0]; String msg = split[1]; Session toSession = clientsMap.get(userId); if (toSession != null) { this.sendMessage(msg, toSession); } } catch (Exception e) { log.error(e.getMessage(), e); } } @OnError public void onError(Session session, Throwable error) { log.error(error.getMessage(), error); } /** * 服务端发送消息给客户端 */ private void sendMessage(String message, Session toSession) { try { log.info("服务端给客户端【" + toSession + "】发送消息:" + message); toSession.getBasicRemote().sendText(message); } catch (Exception e) { log.error("服务端给客户端发送消息失败:", e); } } //关闭连接 @OnClose public void onClose(Session session) { //在线数 -1 onlineCount.decrementAndGet(); clientsMap.remove(session.getId()); log.info("有客户端连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get()); }}
启动类:
package com.study;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * @author biandan * @description * @signature 让天下没有难写的代码 * @create 2021-06-21 下午 8:35 */@SpringBootApplicationpublic class WebSocketApp { public static void main(String[] args) { SpringApplication.run(WebSocketApp.class, args); }}
启动服务,浏览器输入: 分开两个浏览器。
然后输入另外一个客户ID,可以在后台查看:
然后,两个客户端就可以互相通信了。
控制台:
转载地址:http://jkuhf.baihongyu.com/