后台开发:
1. 设置websocket的bean (ServerEndpointExporter)
@SpringBootApplication
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = {"com.medi.websocket","com.medi.util"})
public class WebsocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketApplication.class, args);
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2. 编写websocker
package com.medi.websocket.rest;
import com.medi.util.SpringUtil;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.*;
@Component
@ServerEndpoint(value = "/test") //拦截路径
public class TestWebSocket {
private static final Map<String ,Session> sessionMap=new HashMap<>(16);
@OnOpen //打开连接
@SneakyThrows
public void test(Session session) {
Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
String token = requestParameterMap.get("token").get(0);
sessionMap.put(token, session);
// session.close();
}
@OnMessage //收到消息
@SneakyThrows
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
}
@OnClose //关闭连接
public void onClose(Session session) {
sessionMap.remove(session.getId());
System.out.println("有一连接关闭!当前在线人数为" );
}
@OnError //出错
public void onError(Session session, Throwable error) {
sessionMap.remove(session.getId());
System.out.println("发生错误");
error.printStackTrace();
}
@SneakyThrows
public void sendMessage(String message, String token) {
RabbitTemplate rabbitTemplate = SpringUtil.getBean(RabbitTemplate.class);
//消息队列返回的信息
String back = (String) rabbitTemplate.convertSendAndReceive("test", message);
Session session = sessionMap.get(token);
//websocket发送消息
session.getAsyncRemote().sendText(back);
sessionMap.remove(token);
}
}
3. 前端方法调用
<script type="text/javascript">
var websocket;
// 首先判断是否 支持 WebSocket
if('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/test?token=AA");
} else if('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://localhost:8080/test?token=AA");
} else {
websocket = new SockJS("ws://localhost:8080/test?token=AA");
}
// 打开连接时
websocket.onopen = function(event) {
console.log(" websocket.onopen ");
};
// 收到消息时
websocket.onmessage = function(event) {
console.log("收到一条消息"+event.data);
// alert(event.data);
};
// 出错时
websocket.onerror = function(event) {
console.log(" websocket.onerror ");
};
// 关闭连接时
websocket.onclose = function(event) {
console.log(" websocket.onclose ");
};
</script>