一、DEMO实现
(1)客户端实现。
<button onclick="sendMsg()">发送消息</button>
<script type="text/javascript">
var webSocket = new WebSocket('ws://localhost:8080/TestWebSocket/websocket/' + 'huangwei');
var sendMsg = ()=>{
webSocket.send("I'm Client");
};
webSocket.onerror = ()=>{
console.log('WebSocket连接出错');
}
webSocket.onopen = ()=>{
console.log('WebSocket连接已打开');
}
webSocket.onmessage = (event)=>{
console.log('接收消息: ' + event.data);
}
webSocket.onclose = ()=>{
console.log('Server已关闭');
}
</script>
(2)服务端实现。
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket/{username}")
public class WebSocketServer {
private static Map<String, WebSocketServer> clients = new ConcurrentHashMap<String, WebSocketServer>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) {
this.username = username;
this.session = session;
clients.put("username", this);
System.out.println("client已连接");
}
@OnMessage
public void onMessage(String msg) {
System.out.println("接收消息: " + msg);
for(WebSocketServer client : clients.values()) {
client.session.getAsyncRemote().sendText("I'm Server");
}
}
@OnClose
public void onClose() {
clients.remove(username);
}
@OnError
public void onError(Throwable err) {
System.out.println("WebSocket出错");
}
}
二、SpringMVC实现
(1)添加所需依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
(2)编写WebSocket协议处理器
import org.springframework.web.socket.*;
import java.util.concurrent.ConcurrentHashMap;
public class MyWebSocketHandler implements WebSocketHandler {
private static ConcurrentHashMap<String, WebSocketSession> users = new ConcurrentHashMap<String, WebSocketSession>();
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
users.put(webSocketSession.getId(), webSocketSession);
System.out.println("[+]连接已建立");
}
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
System.out.println("信息: " + webSocketMessage.getPayload().toString());
webSocketSession.sendMessage(new TextMessage("I'm Server"));
}
@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
users.remove(webSocketSession);
webSocketSession.close(closeStatus);
}
//是否支持分包
@Override
public boolean supportsPartialMessages() {
return false;
}
}
(3)配置websocket映射和处理类
<bean id="webSocketHandler" class="cn.edu.yau.controller.MyWebSocketHandler"></bean>
<websocket:handlers>
<websocket:mapping path="/ws/" handler="webSocketHandler"/>
<!--握手Interceptor,拦截部分WebSocket通信-->
<!--
<websocket:handshake-interceptors>
<bean class=""></bean4.>
</websocket:handshake-interceptors>
-->
</websocket:handlers>
<!--注册sockJS,sockJS是Spring提供的对不能使用WebSocket协议的客户端提供一种模拟-->
<websocket:handlers>
<websocket:mapping path="/sockjs/ws/" handler="webSocketHandler"/>
</websocket:handlers>
(4) 前端页面
<button onclick="sendMsg()">发送消息</button>
<script type="text/javascript">
var webSocket = new WebSocket("ws://localhost:8080/ksxt/ws/");
var sendMsg = ()=>{
webSocket.send("I'm Client");
};
webSocket.onerror = ()=>{
console.log('WebSocket连接出错');
}
webSocket.onopen = ()=>{
console.log('WebSocket连接已打开');
}
webSocket.onmessage = (event)=>{
console.log('接收消息: ' + event.data);
}
webSocket.onclose = ()=>{
console.log('Server已关闭');
}
</script>