什么是websocket?
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
Spring Boot和websocket的整合
<!--socket的jar包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Spring Boot常用的几个注解
@ServerEndpoint | 指定的客户端请求的URI |
---|---|
@OnOpen | 建立连接成功调用 |
@OnClose | 关闭连接时调用 |
@OnMessage | 收到客户端消息后调用的方法 |
@OnError | 发生错误触发 |
服务端代码
@Configuration
public class WebSocketConfig {
/**
* 注入一个ServerEndpointExporter,
* 该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
System.out.println("注入对象");
return new ServerEndpointExporter();
}
}
@ServerEndpoint("/websocket/{userId}") // 这个注解的作用就是指定客户端请求的API
@Component
@Slf4j
public class MySocketServer {
//用来存放每个客户端对应的 MySocketServer对象
private static ConcurrentHashMap<String, MySocketServer> webClient = new ConcurrentHashMap<>();
//与某个客户端连接会话,需要它来给客户端发送信息
private Session session;
//用户ID
private String userId;
//建立连接调用
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session) {
this.userId = userId;
this.session = session;
if(webClient.containsKey(userId)){
webClient.remove(userId);
webClient.put(userId,this);
} else{
webClient.put(userId,this);
}
sendMessage("用户为"+this.userId+"连接成功!");
log.info("用户ID为:{}已连接成功!}",userId);
}
//连接断开调用
@OnClose
public void onClose(){
if (webClient.containsKey(userId)){
webClient.remove(userId);
}
log.info("用户iD为:{},已断开连接",userId);
}
//收到客户端信息调用
@OnMessage
public void onMessage(String message,Session session){
log.info("用户信息:"+this.userId+ "报文数据:"+message);
if(!StringUtils.isEmpty(message)){
JSONObject parse = JSON.parseObject(message);
parse.put("userId",this.userId); //标注一下这是哪个客户端发送的信息
String toUserId = parse.getString("toUserId");
if(!StringUtils.isEmpty(toUserId) && webClient.containsKey(toUserId)){
MySocketServer mySocketServer = webClient.get(toUserId); //拿到这个客户端
mySocketServer.sendMessage(parse.toJSONString()); //这个客户端发送信息
}
}
}
// 连接失败调用
@OnError
public void onError(Session session,Throwable throwable){
log.error("用户错误:"+this.userId+"错误信息是:"+throwable.getMessage());
}
//服务器主动推送信息给客户端
public void sendMessage(String message){
try {
this.session.getBasicRemote().sendText(message); //当前的MySocketServer对象,session就是当前用户的信息
} catch (Exception exception){
exception.printStackTrace();
}
log.info("服务端向,用户ID为:{},发送信息成功!",this.userId);
}
}
可以自己写个websocket的HTML页面。能力有线,就百度 websocket在线测试。
本地地址测试:ws://127.0.0.1:8080/ajaxchattest/websocket/test1