SpringBoot简单集成WebSocket(纯后端)
- 引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 编写一个WebSocketConfig
package com.ksxx.test.service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- 编写一个ServerEncoder继承Encoder,这个编译器是为了可以发送对象信息
package com.ksxx.test;
import com.alibaba.fastjson.JSON;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
public class ServerEncoder implements Encoder.Text<Object> {
@Override
public void destroy() {
}
@Override
public void init(EndpointConfig arg0) {
}
@Override
public String encode(Object obj) {
return JSON.toJSONString(obj);
}
}
- 编写一个WebSocketBacklogServer (其中type为类型,可多种连接类型)
package com.ksxx.test;
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.ConcurrentHashMap;
@ServerEndpoint(value="/websocket/{type}/{userId}", encoders = { ServerEncoder.class })
@Component
public class WebSocketBacklogServer {
private static ConcurrentHashMap<String, WebSocketBacklogServer> webSocketSet = new ConcurrentHashMap<String, WebSocketBacklogServer>();
private Session session;
private Integer userId;
private String type;
@OnOpen
public void onOpen(Session session,@PathParam("userId") Integer userId,@PathParam("type") String type) {
this.session = session;
webSocketSet.put(type+","+userId,this);
this.userId=userId;
this.type=type;
}
@OnClose
public void onClose() {
System.out.println(userId+type);
webSocketSet.remove(type+","+userId);
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("收到来自窗口"+userId+"的关于"+type+"信息:"+messag);
}
@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 void sendMessage(Object message) throws EncodeException,IOException {
this.session.getBasicRemote().sendObject(message);
}
public void sendMessageInAll(Object message) throws EncodeException,IOException {
for(WebSocketBacklogServer value : webSocketSet.values()) {
value.session.getBasicRemote().sendObject(message);
}
}
public static void sendInfo(Object message,Integer userId,String type) throws EncodeException,IOException {
webSocketSet.get(type+","+userId).sendMessage(message);
}
}
- 模拟客户端测试连接
测试地址: http://www.jsons.cn/websocket/
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e75975efb43689adc39245468c55fd19.png)
- 模拟客户端测试发送信息
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8906c6f51aed5d58bde2ec5cb61077d8.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bbda6bd7139fc280ad5af7c8ccbe2299.png)
- 服务端主动推送信息(对象类),创建一个Controller写一个测试方法测试调用一下即可
package com.ksxx.test.controller;
import com.ksxx.test.service.WebSocketBacklogServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("test")
public class TestController {
@RequestMapping("aa")
public void aa(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("age",13);
try {
WebSocketBacklogServer.sendInfo(jsonObject,1,"chat");
} catch (Exception e) {
e.printStackTrace();
}
}
}