效果图:
什么是websocket
WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就可以建立一条快速通道,两者就可以实现数据互传了。说白了,就是打破了传统的http协议的无状态传输(只能浏览器请求,服务端响应),websocket全双工通讯,就是浏览器和服务器进行一次握手,浏览器可以随时给服务器发送信息,服务器也可以随时主动发送信息给浏览器了。对webSocket原理有兴趣的客官,可以自行百度。
环境的搭建
<!-- springboot websocket -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1-b07</version>
</dependency>
websocket配置类
@Configuration
public class WebSocketStompConfig{
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
return new ServerEndpointExporter();
}
}
点对点
@RestController
@ServerEndpoint(value = "/webSocketOneToOne/{param}")
public class WebSocketOneToOne {
// 这里使用静态,让 service 属于类
private static UserService userService;
// 注入的时候,给类的 service 注入
@Autowired
public void setUserService(UserService userService) {
WebSocketOneToOne.userService = userService;
}
private static ChatMsgService chatMsgService;
@Autowired
public void setChatMsgService(ChatMsgService chatMsgService) {
WebSocketOneToOne.chatMsgService = chatMsgService;
}
// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount;
//实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key为用户标识
private static Map<String,WebSocketOneToOne> connections = new ConcurrentHashMap<>();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private String role;
private String socketId;
private Integer mobanId;
/**
* 连接建立成功调用的方法
*
* @param session
* 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam("param") String param, Session session) {
this.session = session;
String[] arr = param.split(",");
this.role = arr[0]; //用户标识
this.socketId = arr[1]; //会话标识
this.mobanId = Integer.valueOf(arr[2]); //会话标识
connections.put(role,this); //添加到map中
addOnlineCount(); // 在线数加
// System.out.println(param);
// System.out.println(this.session);
// System.out.println("有新连接加入!新用户:"+role+",当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
connections.remove(role); // 从map中移除
subOnlineCount(); // 在线数减
// System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
* @param session
* 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
// System.out.println("来自客户端的消息:" + message);
JSONObject json= JSON.parseObject(message);
String string = (String) json.get("message"); //需要发送的信息
String to = (String) json.get("role"); //发送对象的用户标识
send(string,role,to,socketId);
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError<