前言:

  最近工作中有一个需求,就是服务端要主动推送消息给客户端,而我们平常的Http请求只能一请求一响应,为此学习了webScokset通讯技术,以下介绍的是java 通过SpringBoot集成webScoket搭建服务端。


1.引入webScoket依赖

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>

2.bean注入

  • ServerEndpointExporter 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
} }

3.创建scoket的Server服务

  创建一个java类 WebScoketServer,以下为我自己写的一个小demo,实现的就是服务端和客户端一个对话(客户端没有搭建用的网页测试),效果我会在下面测试演示。

  其他具体业务逻辑在连接成功或者收到信息后方法里进行处理

@ServerEndpoint("/webSocket/{username}")
@Component
@Slf4j
public class WebScoketServer { //concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>(); private static Map<Session, List<String>> map =new HashMap<>(); //发送消息
public void sendMessage(Session session, String message) throws IOException {
synchronized (session) {
System.out.println("发送数据:" + message);
session.getBasicRemote().sendText(message);
} } //建立连接成功调用
@OnOpen
public void onOpen(Session session, @PathParam(value = "username") String userName){
log.info("连接建立 userName是{}",userName);
sessionPools.put(userName,session);
List<String> list =new ArrayList<>();
list.add("服务端--》哈哈哈建立连接后的回复 ");
map.put(session,list);
try {
sendMessage(session,list.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("连接建立");
} //关闭连接时调用
@OnClose
public void onClose(@PathParam(value = "username") String userName){
log.info("连接关闭 userName是{}",userName);
System.out.println("连接关闭");
} //收到客户端信息后
@OnMessage
public void onMessage(String message,@PathParam(value = "username") String userName) throws IOException{
log.info("收到消息 message是{}",message);
try {
Session session = sessionPools.get(userName);
List<String> list = map.get(session);
list.add("客户端--》"+message+" ");
list.add("服务端--》我收到消息:"+message+" ");
map.put(session,list); sendMessage(session,list.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("收到消息");
} //错误时调用
@OnError
public void onError(Session session, Throwable throwable){
log.info("连接错误");
System.out.println("连接错误");
}
}

4.测试

通过springBoot集成搭建webScoket服务器的更多相关文章

  1. SpringBoot+Mybatis集成搭建

    本博客介绍一下SpringBoot集成Mybatis,数据库连接池使用alibaba的druid,使用SpringBoot微框架虽然集成Mybatis之后可以不使用xml的方式来写sql,但是用惯了x ...

  2. SpringBoot集成RabbitMQ消息队列搭建与ACK消息确认入门

    1.RabbitMQ介绍 RabbitMQ是实现AMQP(高级消息队列协议)的消息中间件的一种,最初起源于金融系统,用于在分布式系统中存储转发消息,在易用性.扩展性.高可用性等方面表现不俗.Rabbi ...

  3. 持续集成之二:搭建SVN服务器(subversion)

    安装环境 Red Hat Enterprise Linux Server release 7.3 (Maipo) jdk1.7.0_80 subversion-1.10.3.tar.gz apr-1. ...

  4. idea 搭建 SpringBoot 集成 mybatis

    编译器:IDEA2018.2.3 环境:win10,jdk1.8,maven3.4 数据库:mysql 5.7 备注:截图较大,如果看不清,可以在图片上右键=>在新标签页中打开   查看高清大图 ...

  5. Windows/Linux 环境搭建Git服务器 + vs2012集成git

    1. 下载.安装Git 我的系统是Windows 7,需要安装Git for Windows. 下载地址: http://code.google.com/p/msysgit/downloads/lis ...

  6. SpringBoot集成ssm-druid-通用mapper

    简单介绍 springboot 首先什么是springboot? springboot是spring的另外一款框架,设计目的是用来简化新的spring应用的搭建和开发时所需要的特定的配置,从而使开发过 ...

  7. 自己家里搭建NAS服务器有什么好方案?

    转自:https://www.zhihu.com/question/21359049 作者:陈二发链接:https://www.zhihu.com/question/21359049/answer/6 ...

  8. Windows Server 2003搭建邮件服务器

    Windows Server 2003搭建邮件服务器 由于Windows Server 2003默认是没有安装我们搭建邮件服务器所需要的POP3和SMTP服务的,因此需要我们自己来安装.方法如下: 1 ...

  9. LUA+resty 搭建验证码服务器

    使用Lua和OpenResty搭建验证码服务器 雨客 2016-04-08 16:38:11 浏览2525 评论0 云数据库Redis版 摘要: Lua下有个Lua-GD图形库,通过简单的Lua语句就 ...

随机推荐

  1. [BUUCTF]REVERSE——[FlareOn4]login

    [FlareOn4]login 附件 步骤: 是个网页,直接打开,查看网页源码 百度了几个函数 charCodeAt(0)是返回当前字符的Unicode 编码 String.fromCharCode返 ...

  2. Windows 任务计划部署 .Net 控制台程序

    Windows 搜索:任务计划程序 创建任务 添加任务名称 设置触发器:这里设置每10分钟执行一次 保存之后显示 此任务会从每天的 0:10:00 执行第一次后一直循环下去. 在操作选项卡下,选择启动 ...

  3. Spring 5| 轻量级的开源JavaEE框架

    一.Spring框架的概述 1.Spring是轻量级的开源的JavaEE框架 2.Spring可以解决企业应用开发的复杂性 3.Spring有两个核心的部分:IOC(控制反转)和AOP(面向切面编程) ...

  4. CF1036D Vasya and Arrays 题解

    Content 给定两个长度分别为 \(n\) 和 \(m\) 的数列 \(A,B\).你需要将两个数列都恰好分成 \(k\) 份,使得两个数列中第 \(i(i\in[1,k])\) 份的元素和对应相 ...

  5. SecureCRT中Vim颜色

    解决方法:1.确认安装了vim-enhancedrpm -qa | grep vim-enhanced2.optins>session optionsTerminal>emulationx ...

  6. 使用 juqery.media.js 实现 pdf 预览

    作用:可以实现在指定的位置预览PDF 缺点: (1)在iPad上只能预览一页PDF.(问题是iPad会将PDF转为img呈现,试了将img宽度设置为100%方法但并不好使) (2)在安卓上不能预览,依 ...

  7. LeetCode1238循环码排列

    题目 给你两个整数 n 和 start.你的任务是返回任意 (0,1,2,,...,2n-1) 的排列 p,并且满足: p[0] = start p[i] 和 p[i+1] 的二进制表示形式只有一位不 ...

  8. Second Order Optimization for Adversarial Robustness and Interpretability

    目录 概 主要内容 (4)式的求解 超参数 Tsiligkaridis T., Roberts J. Second Order Optimization for Adversarial Robustn ...

  9. PlatformIO+Jlink进行调试

    PlatformIO自带调试功能具体配置如下 https://docs.platformio.org/en/latest/plus/debug-tools/jlink.html     我是用的是直接 ...

  10. CS5211替代兼容PS8625|DP转LVDS|CS5211设计方案详解

    PS8625是一个DP显示端口 到LVDS转换器芯片,利用GPU和显示端口(DP) 或嵌入式显示端口(eDP) 输出和接受LVDS输入的显示面板.PS8625实现双通道DP输入,双链路LVDS输出.P ...