1、引入依赖<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-websocket</artifactid></dependency><dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid></dependency><dependency> <groupid>com.alibaba</groupid> <artifactid>fastjson</artifactid> <version>1.2.3</version></dependency>
2、websocketconfig 开启websocketpackage com.shucha.deveiface.web.config; /** * @author tqf * @description * @version 1.0 * @since 2022-04-12 15:35 */import org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration;import org.springframework.web.socket.server.standard.serverendpointexporter; /** * 开启websocket */@configurationpublic class websocketconfig { @bean public serverendpointexporter serverendpointexporter(){ return new serverendpointexporter(); }}
3、websocketserverpackage com.shucha.deveiface.web.ws; /** * @author tqf * @description * @version 1.0 * @since 2022-04-12 15:33 */import lombok.extern.slf4j.slf4j;import org.springframework.stereotype.component;import org.springframework.web.socket.websocketsession; import javax.websocket.*;import javax.websocket.server.pathparam;import javax.websocket.server.serverendpoint;import java.util.arraylist;import java.util.collections;import java.util.list;import java.util.concurrent.concurrenthashmap;import java.util.concurrent.copyonwritearrayset; @component@serverendpoint("/websocket/{userid}")@slf4jpublic class websocketserver { private session session; private string userid; /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/ private static int onlinecount = 0; private static copyonwritearrayset<websocketserver> websocketset = new copyonwritearrayset<>(); /** * concurrent包的线程安全set,用来存放每个客户端对应的mywebsocket对象 */ private static concurrenthashmap<string,websocketserver> websocketmap = new concurrenthashmap(); /** * 为了保存在线用户信息,在方法中新建一个list存储一下【实际项目依据复杂度,可以存储到数据库或者缓存】 */ private final static list<session> sessions = collections.synchronizedlist(new arraylist<>()); /** * 建立连接 * @param session * @param userid */ @onopen public void onopen(session session, @pathparam("userid") string userid) { this.session = session; this.userid = userid; websocketset.add(this); sessions.add(session); if (websocketmap.containskey(userid)) { websocketmap.remove(userid); websocketmap.put(userid,this); } else { websocketmap.put(userid,this); addonlinecount(); } // log.info("【websocket消息】有新的连接, 总数:{}", websocketset.size()); log.info("[连接id:{}] 建立连接, 当前连接数:{}", this.userid, websocketmap.size()); } /** * 断开连接 */ @onclose public void onclose() { websocketset.remove(this); if (websocketmap.containskey(userid)) { websocketmap.remove(userid); subonlinecount(); } // log.info("【websocket消息】连接断开, 总数:{}", websocketset.size()); log.info("[连接id:{}] 断开连接, 当前连接数:{}", userid, websocketmap.size()); } /** * 发送错误 * @param session * @param error */ @onerror public void onerror(session session, throwable error) { log.info("[连接id:{}] 错误原因:{}", this.userid, error.getmessage()); error.printstacktrace(); } /** * 收到消息 * @param message */ @onmessage public void onmessage(string message) { // log.info("【websocket消息】收到客户端发来的消息:{}", message); log.info("[连接id:{}] 收到消息:{}", this.userid, message); } /** * 发送消息 * @param message * @param userid */ public void sendmessage(string message,long userid) { websocketserver websocketserver = websocketmap.get(string.valueof(userid)); if (websocketserver!=null){ log.info("【websocket消息】推送消息, message={}", message); try { websocketserver.session.getbasicremote().sendtext(message); } catch (exception e) { e.printstacktrace(); log.error("[连接id:{}] 发送消息失败, 消息:{}", this.userid, message, e); } } } /** * 群发消息 * @param message */ public void sendmassmessage(string message) { try { for (session session : sessions) { if (session.isopen()) { session.getbasicremote().sendtext(message); log.info("[连接id:{}] 发送消息:{}",session.getrequestparametermap().get("userid"),message); } } } catch (exception e) { e.printstacktrace(); } } /** * 获取当前连接数 * @return */ public static synchronized int getonlinecount() { return onlinecount; } /** * 当前连接数加一 */ public static synchronized void addonlinecount() { websocketserver.onlinecount++; } /** * 当前连接数减一 */ public static synchronized void subonlinecount() { websocketserver.onlinecount--; } }
4、测试连接发送和接收消息package com.shucha.deveiface.web.controller; import com.alibaba.fastjson.jsonobject;import com.shucha.deveiface.web.ws.websocketserver;import lombok.data;import lombok.experimental.accessors;import org.springframework.beans.factory.annotation.autowired;import org.springframework.web.bind.annotation.getmapping;import org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.bind.annotation.restcontroller; /** * @author tqf * @description * @version 1.0 * @since 2022-04-12 15:44 */@restcontroller@requestmapping("/web")public class testwebsocket { @autowired private websocketserver websocketserver; /** * 消息发送测试 */ @getmapping("/test") public void test(){ for (int i=1;i<4;i++) { websocketresponse response = new websocketresponse(); response.setuserid(string.valueof(i)); response.setusername("姓名"+ i); response.setage(i); websocketserver.sendmessage(jsonobject.tojsonstring(response), long.valueof(string.valueof(i))); } } /** * 群发消息测试(给当前连接用户发送) */ @getmapping("/sendmassmessage") public void sendmassmessage(){ websocketresponse response = new websocketresponse(); response.setusername("群发消息模板测试"); websocketserver.sendmassmessage(jsonobject.tojsonstring(response)); } @data @accessors(chain = true) public static class websocketresponse { private string userid; private string username; private int age; }}
5、在线测试地址websocket 在线测试
6、测试截图访问测试发送消息:http://localhost:50041//web/test
测试访问地址:ws://192.168.0.115:50041/websocket/1 wss://192.168.0.115:50041/websocket/2
以上就是springboot怎么实现websocket即时通讯的详细内容。