1.什么是websocket
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。
2.为什么要使用websocket
一张图片就可以感受到它的作用!
其实就是服务端和客户端可以互相发送消息!
3.springboot中集成使用websocket
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
2.添加一个项目支持websocket的配置类
这个配置当然也可以添加到启动类中
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.编写websocket用到的后台服务方法
WebSocket是类似客户端服务端的形式(采用ws协议).其实也就相当于websocket要用到的后台Controller层
直接@ServerEndpoin和@Component启用即可,然后在里面实现@OnOpen,@onClose,@onMessage等方法
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint(value = "/websocket/{sname}")
@Component
public class MyWebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private String name;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sname") String sname) {
this.name=sname;
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入:"+sname+"!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功,当前时间:" + new java.sql.Timestamp(System.currentTimeMillis()));
} catch (IOException e) {
System.out.println("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,@PathParam("sname") String sname) {
System.out.println("来自客户端"+name+"的消息:" + message);
//群发消息
for (MyWebSocket item : webSocketSet) {
try {
item.sendMessage(message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
* */
@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);
}
/**
* 自定义的群发消息,我们可以在其他的类中调用该方法,然后向前台推送消息
* */
public static void sendInfo(@PathParam("sname") String sname,String message) throws IOException {
for (MyWebSocket item : webSocketSet) {
try {
//这里可以设定只推送给这个sname的,为null则全部推送
if(sname==null) {
item.sendMessage(message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
}else if(item.name.equals(sname)){
item.sendMessage(message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
4.编写前台页面
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
<script src="../js/jquery.min.js"></script>
</head>
<body>
Welcome <input id="name" type="text" /><button onclick="concat()">concat</button><br/>
<input id="text" type="text" /><button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
function concat() {
var name = document.getElementById('name').value;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8084/websocket/"+name+"");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("socket连接失败");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("socket连接已打开");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("socket连接已关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML +"<br/>";
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
我这里是先输入名字,然后点击连接,在下面的输入框填写内容,就是发送给所有的当前在线的客户端!
5.测试结果
1.在浏览器中打开2个页面,输入张三,李四然后连接
2.输入内容发送,发送测试消息
3.实现单独给某一个人发消息
新建一个控制层,编写方法
//推送数据接口
@ResponseBody
@RequestMapping("/socket/push/{sname}")
public String pushToWeb(@PathVariable String sname, String message) {
try {
MyWebSocket.sendInfo(sname,message);
} catch (IOException e) {
e.printStackTrace();
return "推送失败";
}
return "推送成功"+sname;
}
这里我们可以看到调用了MyWebSocket中的自定义群发消息的方法,然后我们在浏览器调用这个方法
http://localhost:8084//socket/push/张三?message=单独发送消息给张三
我们发现这时候只推送给了张三,这时候我们再打开张三的页面
而李四是没有收到的
这样其实也就实现了所谓的群发和单独聊天的意思了!
这是我的一个小项目:
https://github.com/ZGQ1996/websocket.git