什么是WebSocket?
百度百科解析:WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
需求说明:
当客户使用客户端在商品页面选择好自己的心意的商品进行下单后,我们需要有一个业务需求,就是客户已下单付款后,我们系统自动给卖家端提示一个消息,有新的订单生成,提醒卖家及时处理的情景。这里采用的是使用websocket来实时进行。
接下来,使用简单的例子进行展示(说明:文中例子部分引用别人文章中的例子),最终在结合自己项目需要进行具体的操作!文中的例子是基于maven进行jar管理的,项目中的是使用springboot整合websocket。接下来,我们就直接代码:
1、引入pom
websocket核心是@ServerEndpoint这个注解。这个注解是Javaee标准里的注解,tomcat7以上已经对其进行了实现,如果是用传统方法使用tomcat发布项目,只要在pom文件中引入javaee标准即可使用。
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
当我们使用springboot进行整合的话,就不需要在引入javaee-api了,springboot的高级组件会自动引用基础的组件,spring-boot-starter-websocket就引入了spring-boot-starter-web和spring-boot-starter。使用springboot的websocket功能首先引入springboot组件,因为我们例子中会用到前端页面,这里我们使用thymeleaf进行整合:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
我们使用idea点击上面引入的坐标,会发现springboot已经帮我们引入了其他的jar包,所以不要重复引入,否则会引起jar冲突。
2、创建javabean配置(WebSocketConfig---->ServerEndpointExporter ),注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,如果使用独立的servlet容器,因为它将由容器自己提供和管理。
@Component
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
接下来我们就写websocket后台代码的实现:
//前端请求后台的路径
@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户id
private static ConcurrentHashMap<String, WebSocket> webSocketSet = new ConcurrentHashMap<String, WebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//当前发消息的人员编号
private String userId = "";
/**
* 线程安全的统计在线人数
*
* @return
*/
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
/**
* 连接建立成功调用的方法
* @param param 用户唯一标示
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam(value = "userId") String param, Session session) {
userId = param;//接收到发送消息的人员编号
this.session = session;
webSocketSet.put(param, this);//加入线程安全map中
addOnlineCount(); //在线数加1
System.out.println("用户id:" + param + "加入连接!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!userId.equals("")) {
webSocketSet.remove(userId); //根据用户id从ma中删除
subOnlineCount(); //在线数减1
System.out.println("用户id:" + userId + "关闭连接!当前在线人数为" + getOnlineCount());
}
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//要发送人的用户uuid
String sendUserId = message.split(",")[1];
//发送的信息
String sendMessage = message.split(",")[0];
//给指定的人发消息
sendToUser(sendUserId, sendMessage);
}
/**
* 给指定的人发送消息
* @param message
*/
public void sendToUser(String sendUserId, String message) {
try {
if (webSocketSet.get(sendUserId) != null) {
webSocketSet.get(sendUserId).sendMessage(userId + "给我发来消息,消息内容为--->>" + message);
} else {
if (webSocketSet.get(userId) != null) {
webSocketSet.get(userId).sendMessage("用户id:" + sendUserId + "以离线,未收到您的信息!");
}
System.out.println("消息接受人:" + sendUserId + "已经离线!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 管理员发送消息
* @param message
*/
public void systemSendToUser(String sendUserId, String message) {
try {
if (webSocketSet.get(sendUserId) != null) {
webSocketSet.get(sendUserId).sendMessage("系统给我发来消息,消息内容为--->>" + message);
} else {
System.out.println("消息接受人:" + sendUserId + "已经离线!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 给所有人发消息
* @param message
*/
private void sendAll(String message) {
String sendMessage = message.split(",")[0];
//遍历HashMap
for (String key : webSocketSet.keySet()) {
try {
//判断接收用户是否是当前发消息的用户
if (!userId.equals(key)) {
webSocketSet.get(key).sendMessage("用户:" + userId + "发来消息:" + " <br/> " + sendMessage);
System.out.println("key = " + key);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 发送消息
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
//同步发送
this.session.getBasicRemote().sendText(message);
//异步发送
//this.session.getAsyncRemote().sendText(message);
}
}
3、前端代码:
这里为了更加直观,我们用两个页面进行交互,更能体现出来websocket的实时:
websocket1.html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket SpringBootDemo</title>
</head>
<body>
<!--userId:发送消息人的编号-->
<div>默认用户id:001(后期可以根据业务逻辑替换)</div>
<br/><input id="text" type="text"/>
<input placeholder="请输入接收人的用户id" id="sendUserId"></input>
<button onclick="send()">发送消息</button>
<br/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<br/>
<div>WebSocket链接1</div>
<br/>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
var userId = "001"
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1:8080/websocket/" + userId);
}
else {
alert('当前浏览器不支持websocket哦!')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(sendMessage) {
document.getElementById('message').innerHTML += sendMessage + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;//要发送的消息内容
if (message == "") {
alert("发送信息不能为空!")
return;
} //获取发送人用户id
var sendUserId = document.getElementById('sendUserId').value;
if (sendUserId == "") {
alert("发送人用户id不能为空!")
return;
}
document.getElementById('message').innerHTML += (userId + "给" + sendUserId + "发送消息,消息内容为---->>" + message + '<br/>');
message = message + "," + sendUserId//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
websocket.send(message);
}
</script>
</html>
websocket2.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<title>WebSocket SpringBootDemo</title>
</head>
<body>
<!--userId:发送消息人的编号-->
<div>默认用户id:002(后期可以根据业务逻辑替换)</div>
<br/><input id="text" placeholder="请输入要发送的信息" type="text"/>
<input placeholder="请输入接收人的用户id" id="sendUserId"></input>
<button onclick="send()">发送消息</button>
<br/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<br/>
<div>WebSocket链接2</div>
</br>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
var userId = "002"
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1:8080/websocket/" + userId);
}
else {
alert('当前浏览器不支持websocket哦!')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(sendMessage) {
document.getElementById('message').innerHTML += sendMessage + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;//要发送的消息内容
if (message == "") {
alert("发送信息不能为空!")
return;
} //获取发送人用户id
var sendUserId = document.getElementById('sendUserId').value;
if (sendUserId == "") {
alert("发送人用户id不能为空!")
return;
}
document.getElementById('message').innerHTML += ("我给" + sendUserId + "发送消息,消息内容为---->>" + message + '<br/>');
message = message + "," + sendUserId//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
websocket.send(message);
}
</script>
</html>
controller层进行页面跳转:
@Controller
public class IndexController {
@RequestMapping(value = "/ws")
public String ws() {
return "websocket1";
}
@RequestMapping(value = "/ws1")
public String ws1() {
return "websocket2";
}
}
项目运行起来,看下最后效果图:
在项目中springboot已经做了深度的集成和优化,要注意是否添加了不需要的依赖、配置或声明。只要细心耐心点,实际大部分异常我们都是可以避免的,也希望大家养成标记出现的异常,以防下次出现的时候,弄的我们慌里慌张的。特此,整合websocket到此结束。
参考来源:
springboot整合websocket,一篇不错的文章。
在整合过程中也是碰到了一个jar包冲突异常,当时也是着急忙慌的,最后也是耐心的解决了,具体请查看:
springboot整合websocket出现的NoSuchMethodError异常