1.pom文件导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.0.4.RELEASE</version> </dependency>
2.创建webSocket相关配置
package com.example.demo.mainDemo; import org.springframework.context.annotation.Configuration; 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; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "myHandler").setAllowedOrigins("*"); } public WebSocketHandler myHandler() { return new MyHandler(); } }
3.编写webSocket处理类,类似controller接口
package com.example.demo.mainDemo; import com.alibaba.fastjson.JSONObject; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.util.HashMap; import java.util.Map; /** * 相当于controller的处理器 */ public class MyHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); // Map<String, String> map = JSONObject.parseObject(payload, HashMap.class); // System.out.println("=====接受到的数据"+map); session.sendMessage(new TextMessage("服务器返回收到的信息," + payload));
}
}
4.编写客户端
package com.example.demo.mainDemo.client; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.websocket.*; @ClientEndpoint public class MyClient { private static Logger logger = LoggerFactory.getLogger(MyClient.class); private Session session; @OnOpen public void open(Session session){ logger.info("Client WebSocket is opening..."); this.session = session; } @OnMessage public void onMessage(String message){ logger.info("Server send message: " + message); } @OnClose public void onClose(){ logger.info("Websocket closed"); } /** * 发送客户端消息到服务端 * @param message 消息内容 */ public void send(String message){ this.session.getAsyncRemote().sendText(message); } }
5.创建main方法
package com.example.demo.mainDemo.client; import javax.websocket.ContainerProvider; import javax.websocket.WebSocketContainer; import java.net.URI; public class ClientStart { public static void main(String[] args){ try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); MyClient client = new MyClient(); container.connectToServer(client, new URI("ws://127.0.0.1:8080/myHandler")); // container.setDefaultMaxSessionIdleTimeout(5000L); int turn = 0; while(turn++ < 10){ client.send("client send: 客户端消息 " + turn); Thread.sleep(1000); } }catch (Exception e){ e.printStackTrace(); } } }
6.执行main方法