实现场景:每在小程序中添加一条数据时,后台将主动推送一个标记给PC端,PC端接收到标记将进行自动播放音频。
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();
}
}
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {
private static final CopyOnWriteArraySet<WebSocketServer> connections = new CopyOnWriteArraySet<>();
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
connections.add(this);
this.sendMessage("0");
}
@OnClose
public void onClose() {
connections.remove(this);
System.out.println("连接关闭: " + session.getId());
}
@OnError
public void onError(Throwable error) {
System.out.println("错误信息:"+error.getMessage());
error.printStackTrace();
}
private void sendMessage(String message) {
try {
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void broadcast(String message) {
for (WebSocketServer client : connections) {
client.sendMessage(message);
}
}
}
@Override
public void addUser(req req) {
QueryWrapper<User> userWrapper = new QueryWrapper<>();
userWrapper .eq("name",req.getName());
User u = userMapper.selectOne(userWrapper);
if (u == null){
WebSocketServer.broadcast("1");
}
}
每次小程序调用 addUser() 方法时,都会执行 WebSocketServer.broadcast("1"); 这时候触发主动推送消息给PC端。
遇到的问题:
Error during WebSocket handshske: Unexpected response code: 200
解决方案:
本地项目中存在账号密码验证的过滤器,其中 /websocket 进行了转发,所以需要过滤请求
重新启动项目即可。