什么是websocket?

websocket协议是基于tcp的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。
为什么需要 websocket?
初次接触 websocket 的人,都会问同样的问题:我们已经有了 http 协议,为什么还需要另一个协议?它能带来什么好处?
答案很简单,因为 http 协议有一个缺陷:通信只能由客户端发起,http 协议做不到服务器主动向客户端推送信息。

举例来说,我们想要查询当前的排队情况,只能是页面轮询向服务器发出请求,服务器返回查询结果。轮询的效率低,非常浪费资源(因为必须不停连接,或者 http 连接始终打开)。因此websocket 就是这样发明的。 前言
2020-10-20 教程补充:
- 补充关于
@component和@serverendpoint关于是否单例模式等的解答,感谢大家热心提问和研究。 vue版本的websocket连接方法
2020-01-05 教程补充:
- 整合了
im相关的优化 - 优化
开启/关闭连接的处理 - 上传到
开源项目spring-cloud-study-websocket,方便大家下载代码。
感谢大家的支持和留言,14w访问量是满满的动力!接下来还会有websocket+redis集群优化篇针对多ws服务器做简单优化处理,敬请期待!
话不多说,马上进入干货时刻。
maven依赖
springboot2.0对websocket的支持简直太棒了,直接就有包可以引入
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.web.socket.server.standard.serverendpointexporter;
/**
* 开启websocket支持
* @author zhengkai.blog.csdn.net
*/
@configuration
public class websocketconfig {
@bean
public serverendpointexporter serverendpointexporter() {
return new serverendpointexporter();
}
}
websocketconfig
启用websocket的支持也是很简单,几句代码搞定
import org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration;import org.springframework.web.socket.server.standard.serverendpointexporter;/** * 开启websocket支持 * @author zhengkai.blog.csdn.net */@configuration public class websocketconfig { @bean public serverendpointexporter serverendpointexporter() { return new serverendpointexporter(); } }
websocketserver
这就是重点了,核心都在这里。
- 因为websocket是类似客户端服务端的形式(采用ws协议),那么这里的websocketserver其实就相当于一个ws协议的controller
- 直接
@serverendpoint("/imserver/{userid}")、@component启用即可,然后在里面实现@onopen开启连接,@onclose关闭连接,@onmessage接收消息等方法。 - 新建一个
concurrenthashmapwebsocketmap 用于接收当前userid的websocket,方便im之间对userid进行推送消息。单机版实现到这里就可以。 集群版(多个ws节点)还需要借助mysql或者redis等进行处理,改造对应的sendmessage方法即可。
package com.softdev.system.demo.config;
import java.io.ioexception;
import java.util.concurrent.concurrenthashmap;
import javax.websocket.onclose;
import javax.websocket.onerror;
import javax.websocket.onmessage;
import javax.websocket.onopen;
import javax.websocket.session;
import javax.websocket.server.pathparam;
import javax.websocket.server.serverendpoint;
import com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonobject;
import org.apache.commons.lang.stringutils;
import org.springframework.stereotype.component;
import cn.hutool.log.log;
import cn.hutool.log.logfactory;
/**
* @author zhengkai.blog.csdn.net
*/
@serverendpoint("/imserver/{userid}")
@component
public class websocketserver {
static log log=logfactory.get(websocketserver.class);
/**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
private static int onlinecount = 0;
/**concurrent包的线程安全set,用来存放每个客户端对应的mywebsocket对象。*/
private static concurrenthashmap<string,websocketserver> websocketmap = new concurrenthashmap<>();
/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
private session session;
/**接收userid*/
private string userid="";
/**
* 连接建立成功调用的方法*/
@onopen
public void onopen(session session,@pathparam("userid") string userid) {
this.session = session;
this.userid=userid;
if(websocketmap.containskey(userid)){
websocketmap.remove(userid);
websocketmap.put(userid,this);
//加入set中
}else{
websocketmap.put(userid,this);
//加入set中
addonlinecount();
//在线数加1
}
log.info("用户连接:"+userid+",当前在线人数为:" + getonlinecount());
try {
sendmessage("连接成功");
} catch (ioexception e) {
log.error("用户:"+userid+",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@onclose
public void onclose() {
if(websocketmap.containskey(userid)){
websocketmap.remove(userid);
//从set中删除
subonlinecount();
}
log.info("用户退出:"+userid+",当前在线人数为:" + getonlinecount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@onmessage
public void onmessage(string message, session session) {
log.info("用户消息:"+userid+",报文:"+message);
//可以群发消息
//消息保存到数据库、redis
if(stringutils.isnotblank(message)){
try {
//解析发送的报文
jsonobject jsonobject = json.parseobject(message);
//追加发送人(防止串改)
jsonobject.put("fromuserid",this.userid);
string touserid=jsonobject.getstring("touserid");
//传送给对应touserid用户的websocket
if(stringutils.isnotblank(touserid)&&websocketmap.containskey(touserid)){
websocketmap.get(touserid).sendmessage(jsonobject.tojsonstring());
}else{
log.error("请求的userid:"+touserid+"不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
}catch (exception e){
e.printstacktrace();
}
}
}
/**
*
* @param session
* @param error
*/
@onerror
public void onerror(session session, throwable error) {
log.error("用户错误:"+this.userid+",原因:"+error.getmessage());
error.printstacktrace();
}
/**
* 实现服务器主动推送
*/
public void sendmessage(string message) throws ioexception {
this.session.getbasicremote().sendtext(message);
}
/**
* 发送自定义消息
* */
public static void sendinfo(string message,@pathparam("userid") string userid) throws ioexception {
log.info("发送消息到:"+userid+",报文:"+message);
if(stringutils.isnotblank(userid)&&websocketmap.containskey(userid)){
websocketmap.get(userid).sendmessage(message);
}else{
log.error("用户"+userid+",不在线!");
}
}
public static synchronized int getonlinecount() {
return onlinecount;
}
public static synchronized void addonlinecount() {
websocketserver.onlinecount++;
}
public static synchronized void subonlinecount() {
websocketserver.onlinecount--;
}
}
消息推送
至于推送新信息,可以再自己的controller写个方法调用websocketserver.sendinfo();即可
import com.softdev.system.demo.config.websocketserver;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.servlet.modelandview;
import java.io.ioexception;
/**
* websocketcontroller
* @author zhengkai.blog.csdn.net
*/
@restcontroller
public class democontroller {
@getmapping("index")
public responseentity<string> index(){
return responseentity.ok("请求成功");
}
@getmapping("page")
public modelandview page(){
return new modelandview("websocket");
}
@requestmapping("/push/{touserid}")
public responseentity<string> pushtoweb(string message, @pathvariable string touserid) throws ioexception {
websocketserver.sendinfo(message,touserid);
return responseentity.ok("msg send success");
}
}
页面发起
页面用js代码调用websocket,当然,太古老的浏览器是不行的,一般新的浏览器或者谷歌浏览器是没问题的。还有一点,记得协议是ws的,如果使用了一些路径类,可以replace(“http”,“ws”)来替换协议。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>websocket通讯</title>
</head>
<script src="http://www.51sjk.com/Upload/Articles/1/0/255/255243_20210628002906242.js"></script>
<script>
var socket;
function opensocket() {
if(typeof(websocket) == "undefined") {
console.log("您的浏览器不支持websocket");
}else{
console.log("您的浏览器支持websocket");
//实现化websocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new websocket("ws://localhost:8888/xxxx/im/25");
//var socketurl="${request.contextpath}/im/"+$("#userid").val();
var socketurl="http://localhost:9999/demo/imserver/"+$("#userid").val();
socketurl=socketurl.replace("https","ws").replace("http","ws");
console.log(socketurl);
if(socket!=null){
socket.close();
socket=null;
}
socket = new websocket(socketurl);
//打开事件
socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new date());
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
}
}
function sendmessage() {
if(typeof(websocket) == "undefined") {
console.log("您的浏览器不支持websocket");
}else {
console.log("您的浏览器支持websocket");
console.log('{"touserid":"'+$("#touserid").val()+'","contenttext":"'+$("#contenttext").val()+'"}');
socket.send('{"touserid":"'+$("#touserid").val()+'","contenttext":"'+$("#contenttext").val()+'"}');
}
}
</script>
<body>
<p>【userid】:<div><input id="userid" name="userid" type="text" value="10"></div>
<p>【touserid】:<div><input id="touserid" name="touserid" type="text" value="20"></div>
<p>【touserid】:<div><input id="contenttext" name="contenttext" type="text" value="hello websocket"></div>
<p>【操作】:<div><a onclick="opensocket()">开启socket</a></div>
<p>【操作】:<div><a onclick="sendmessage()">发送消息</a></div>
</body>
</html>
运行效果
- v20200105,加入开源项目spring-cloud-study-websocket,更新运行效果,更方便理解。
- v1.1的效果,刚刚修复了日志,并且支持指定监听某个端口,代码已经全部更新,现在是这样的效果
打开两个页面,按f12调出控控制台查看测试效果:
| 页面 | 参数 |
|---|---|
| http://localhost:9999/demo/page | fromuserid=10,touserid=20 |
| http://localhost:9999/demo/page | fromuserid=20,touserid=10 |
分别开启socket,再发送消息


2. 向前端推送数据:
http://localhost:9999/demo/push/10?message=123123

通过调用push api,可以向指定的userid推送信息,当然报文这里乱写,建议规定好格式。
后续
针对简单im的业务场景,进行了一些优化,可以看后续的文章springboot2+websocket之聊天应用实战(优化版本)(v20201005已整合)
主要变动是copyonwritearrayset改为concurrenthashmap,保证多线程安全同时方便利用map.get(userid)进行推送到指定端口。
相比之前的set,set遍历是费事且麻烦的事情,而map的get是简单便捷的,当websocket数量大的时候,这个小小的消耗就会聚少成多,影响体验,所以需要优化。在im的场景下,指定userid进行推送消息更加方便。
websocker注入bean问题
关于这个问题,可以看最新发表的这篇文章,在参考和研究了网上一些攻略后,项目已经通过该方法注入成功,大家可以参考。
springboot 使用 jsr 303 对 controller 控制层校验及 service 服务层 aop 校验 使用消息资源文件对消息国际化
netty-websocket-spring-boot-starter
springboot2构建基于netty的高性能websocket服务器(netty-websocket-spring-boot-starter)
只需要换个starter即可实现高性能websocket,赶紧使用吧
springboot2+netty+websocket
springboot2+netty实现websocket,使用官方的netty-all的包,比原生的websocket更加稳定更加高性能,同等配置情况下可以handle更多的连接。
代码样式全部已经更正,也支持websocket连接url带参数功能,另外也感谢大家的阅读和评论,一起进步,谢谢!~~
serverendpointexporter错误
org.springframework.beans.factory.beancreationexception: error creating bean with name ‘
serverendpointexporter' defined in class path resource [com/xxx/websocketconfig.class]: invocation of init method failed; nested exception is java.lang.illegalstateexception: javax.websocket.server.servercontainer not available
感谢@来了老弟儿 的反馈:
如果tomcat部署一直报这个错,请移除 websocketconfig 中@bean serverendpointexporter 的注入 。
serverendpointexporter 是由spring官方提供的标准实现,用于扫描serverendpointconfig配置类和@serverendpoint注解实例。使用规则也很简单:
如果使用默认的嵌入式容器 比如tomcat 则必须手工在上下文提供serverendpointexporter。如果使用外部容器部署war包,则不需要提供提供serverendpointexporter,因为此时springboot默认将扫描服务端的行为交给外部容器处理,所以线上部署的时候要把websocketconfig中这段注入bean的代码注掉。 正式项目的前端websocket框架 goeasy
感谢kkatrina的补充,正式的项目中,一般是用第三方websocket框架来做,稳定性、实时性有保证的多,也会包括一些心跳、重连机制。
goeasy专注于服务器与浏览器,浏览器与浏览器之间消息推送,完美兼容世界上的绝大多数浏览器,包括ie6, ie7之类的非常古老的浏览器。支持uniapp,各种小程序,react,vue等所有主流web前端技术。
goeasy采用 发布/订阅 的消息模式,帮助您非常轻松的实现一对一,一对多的通信。
https://www.goeasy.io/cn/doc/
@component和@serverendpoint关于是否单例模式,能否使用static map等一些问题的解答
看到大家都在热心的讨论关于是否单例模式这个问题,请大家相信自己的直接,如果websocket是单例模式,还怎么服务这么多session呢。
- websocket是
原型模式,@serverendpoint每次建立双向通信的时候都会创建一个实例,区别于spring的单例模式。spring的@component默认是单例模式,请注意,默认而已,是可以被改变的。 - 这里的
@component仅仅为了支持@autowired依赖注入使用,如果不加则不能注入任何东西,为了方便。 - 什么是
prototype 原型模式? 基本就是你需要从a的实例得到一份与a内容相同,但是又互不干扰的实例b的话,就需要使用原型模式。关于在原型模式下使用static 的websocketmap,请注意这是concurrenthashmap ,也就是线程安全/线程同步的,而且已经是静态变量作为全局调用,这种情况下是ok的,或者大家如果有顾虑或者更好的想法的化,可以进行改进。 - 例如使用一个中间类来接收和存放session。为什么每次都@onopen都要检查
websocketmap.containskey(userid),首先了为了代码强壮性考虑,假设代码以及机制没有问题,那么肯定这个逻辑是废的对吧。 - 但是实际使用的时候发现偶尔会出现重连失败或者其他原因导致之前的session还存在,这里就做了一个
清除旧session,迎接新session的功能。
vue版本的websocket连接
感谢**@gzrstudy**的贡献,供大家参考。
<script>
export default {
data() {
return {
socket:null,
userid:localstorage.getitem("ms_uuid"),
touserid:'2',
content:'3'
}
},
methods: {
opensocket() {
if (typeof websocket == "undefined") {
console.log("您的浏览器不支持websocket");
} else {
console.log("您的浏览器支持websocket");
//实现化websocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new websocket("ws://localhost:8888/xxxx/im/25");
//var socketurl="${request.contextpath}/im/"+$("#userid").val();
var socketurl =
"http://localhost:8081/imserver/" + this.userid;
socketurl = socketurl.replace("https", "ws").replace("http", "ws");
console.log(socketurl);
if (this.socket != null) {
this.socket.close();
this.socket = null;
}
this.socket = new websocket(socketurl);
//打开事件
this.socket = new websocket(socketurl);
//打开事件
this.socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new date());
};
//获得消息事件
this.socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
this.socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
this.socket.onerror = function() {
console.log("websocket发生了错误");
};
}
},
sendmessage() {
if (typeof websocket == "undefined") {
console.log("您的浏览器不支持websocket");
} else {
console.log("您的浏览器支持websocket");
console.log(
'{"touserid":"' +
this.touserid +
'","contenttext":"' +
this.content +
'"}'
);
this.socket.send(
'{"touserid":"' +
this.touserid +
'","contenttext":"' +
this.content +
'"}'
);
}
}
到此这篇关于springboot2.0集成websocket实现后台向前端推送信息的文章就介绍到这了,更多相关springboot2.0集成websocket内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
再也不会用心爱