WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。
springboot下集成非常容易只需要添加依赖即可。
<!-- websocket 模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
后台websocket配置类:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
*
* 使用@SpringBootApplication启动类进行启动时需要下面这段代码,但生成war包部署在tomcat中不需要这段
* 若打成war包使用tomcat运行的话,则注释掉这个类中serverEndpointExporter 方法.
*
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
以jar执行时需要添加此代码,如果以war执行时添加此代码会报错,所以可以注释掉;
websocket服务类:
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
//@ServerEndpoint("/websocket/{user}")
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
public static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功...");
} catch (IOException e) {
System.out.println("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message) throws IOException {
System.out.println(message);
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
前端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
socket = new WebSocket("ws://localhost:8080/invo/websocket");
//打开事件
socket.onopen = function() {
console.log("webSocket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 调后台获取
//getCallingList();
};
//关闭事件
socket.onclose = function() {
console.log("webSocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("webSocket发生了错误");
}
/* $(window).unload(function() {
socket.close();
}); */
$("#btnSend").click(function() {
socket.send("这是来自客户端的消息" + new Date());
console.log("这是来自客户端的消息" + new Date());
});
$("#btnClose").click(function() {
socket.close();
});
}
});
</script>
</head>
<body>
<button id="btnSend">推送消息</button>
----------------------
<button id="btnClose">关闭连接</button>
</body>
</html>
websockt目前在各个浏览器到终端支持性并不好, 只有IE 10+, FF 34+, Chrome 31+, Safari 7.1+, Android Browser 4.4+ 才得到支持;博主使用的是Chrome进行测试。
打开前端页面,F12打开控制台,可以看到连接成功:
前端输出:
后台输出:
点击“推送消息”按钮:
前端输出:
后台输出:
点击“关闭连接”按钮:
前端输出:
后端输出:
如何后端主动推向前端呢? 其实操作也很方便,因为在WebSocketServer中,我们已经将创建的每个连接对象放到
CopyOnWriteArraySet集合当中,只需要遍历其中的对象调用对应的方法,即可向前端主动推送消息。
这时候我们写一个Controller,模拟一下调用过程。
Controller代码:
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class WebSocketController {
@RequestMapping(value = "/pushMsgToHtml",method = RequestMethod.GET)
@ResponseBody
public String pushMsgToHtml() throws IOException{
CopyOnWriteArraySet<WebSocketServer> webSocketSet = WebSocketServer.webSocketSet;
for(WebSocketServer webSocketServer : webSocketSet){
webSocketServer.sendMessage("你好客户端.....我是服务端");
}
return "200";
}
}
测试一下效果,客户端和服务店建立webSocket连接,然后输入url,http://ip:port/项目名/pushMsgToHtml,页面上显示200,然后我们查看客户端的控制台。
如果我们开启多个客户端,比如打开三个页面:
后台可以看到:
这时候我们让服务端主动推送消息,三个页面均会受到服务端发送的消息;
服务端成功主动推送消息到客户端,但是这样的一种方式是类似于群发,将集合中所有的连接对象都遍历出来,然后进行消息推送。当然这是不符合实际,实际中我们肯定会遇到这样的需求,推送消息给指定的客户端或者是特定的客户端,如果遍历肯定不行了。
在这里博主有个解决方案,是一种比较简单的做法,将CopyOnWriteArraySet更替成ConcurrentHashMap,用map来存储连接对象,每次指定一个唯一key,服务端保存这个key所对应的连接对象,前端将key放到全局变量里面,这样就可以做到一一对应,且服务端也可以根据key拿到指定的连接对象进行消息推送了。
当时项目比较赶,便没有想更好的解决方案,以此方案解决了现有问题。