服务端实现
原生注解
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Configuration
@EnableWebSocket
public class WSConfig {
@Bean
public ServerEndpointExporter serverEndpoint() {
return new ServerEndpointExporter();
}
}
@ServerEndpoint("/ws")
@Component
public class WsServerEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("链接成功");
}
@OnClose
public void onClose(Session session) {
System.out.println("链接关闭");
}
@OnMessage
public void onMessage(Session session, String text) throws IOException {
System.out.println("收到消息:" + text);
session.getBasicRemote().sendText("hello world");
}
}
Spring封装中导入WebSocket
- 导入依赖
- 创建 handler
- 创建 interceptor
- 创建 配置类
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
package com.go.WebSocketDemo;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
@Component
public class MyWebSocketHandler implements WebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("hello user");
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
package com.go.WebSocketDemo;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;
@Component
public class MyWebSocketInterceptors implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
System.out.println("hello hands");
返回 false 会导致连接失败
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}
package com.go.WebSocketDemo.Config;
import com.go.WebSocketDemo.MyWebSocketHandler;
import com.go.WebSocketDemo.MyWebSocketInterceptors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.annotation.Resource;
import javax.websocket.server.ServerEndpoint;
import java.nio.channels.ServerSocketChannel;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Resource
WebSocketHandler defaultHandler;
@Resource
MyWebSocketInterceptors defaultInterceptors;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
System.out.println("hello work");
registry
.addHandler(defaultHandler, "ws")
.addInterceptors(defaultInterceptors)
.setAllowedOrigins("*");
}
}
客户端实现
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</dependency>
package com.go.client;
import java.net.URI;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BaseWebsocketClient extends WebSocketClient {
private static Logger logger = LoggerFactory.getLogger(BaseWebsocketClient.class);
public BaseWebsocketClient(URI serverUri) {
super(serverUri);
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
logger.info(">>>>>>>>>>>websocket open");
}
@Override
public void onMessage(String s) {
logger.info(">>>>>>>>>> websocket message");
System.out.println(s);
}
@Override
public void onClose(int i, String s, boolean b) {
logger.info(">>>>>>>>>>>websocket close");
}
@Override
public void onError(Exception e) {
logger.error(">>>>>>>>>websocket error {}",e);
}
}
public class main {
public static void main(String[] args) {
try {
BaseWebsocketClient myClient = new BaseWebsocketClient(new URI("ws://127.0.0.1:8080/ws"));
myClient.connect();
while (!myClient.getReadyState().equals(ReadyState.OPEN)) {
System.out.println("连接中。。。");
Thread.sleep(1000);
}
JSONObject object = new JSONObject();
object.put("message", "success连接");
myClient.send("是我啊");
System.out.println("...");
} catch (Exception e) {
e.printStackTrace();
}
}
}