springboot和websocket通讯时的坑有一个:下面这个东西要有
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* Created with IntelliJ IDEA.
*
* @author: xincheng.zhao
* @date: 2018/9/4
* @description:
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
spring里面还有创建下面的:
@ServerEndpoint(value = "/websocket")
@Component
public class WSController {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WSController> webSocketSet = new CopyOnWriteArraySet<WSController>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
System.out.println("有新连接加入!当前在线人数为");
}
//
// //连接打开时执行
// @OnOpen
// public void onOpen(@PathParam("user") String user, Session session) {
// currentUser = user;
// System.out.println("Connected ... " + session.getId());
// }
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
System.out.println("websocket close");
}
/*
*收到客户端消息
*/
@OnMessage
public void onMessage(String message ,Session session){
System.out.println("收到客户端的消息:"+message);
}
}
js里面实现:
layim.on("sendMessage",function (res) {
ws.send(JSON.stringify({
type:"chatMessage",
data:res
}))
layer.msg("发送消息成功")
})
其他要配置好