springboot实现websocket即时通讯的示例代码-亚博电竞手机版

目录

  • 1、引入依赖
  • 2、websocketconfig 开启websocket
  • 3、websocketserver
  • 4、测试连接发送和接收消息
  • 5、在线测试地址
  • 6、测试截图

1、引入依赖

org.springframework.boot spring-boot-starter-websocket org.projectlombok lombok com.alibaba fastjson 1.2.3

2、websocketconfig 开启websocket

package 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 */ @configuration public class websocketconfig { @bean public serverendpointexporter serverendpointexporter(){ return new serverendpointexporter(); } }

3、websocketserver

package 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;ngframework.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即时通讯的示例代码的文章就介绍到这了,更多相关springboot websocket即时通讯内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

展开全文
内容来源于互联网和用户投稿,文章中一旦含有亚博电竞手机版的联系方式务必识别真假,本站仅做信息展示不承担任何相关责任,如有侵权或涉及法律问题请联系亚博电竞手机版删除

最新文章

网站地图