使用Java WebSocket进行实时通信案例分享

原创 ゝ一世哀愁。 2024-10-09 19:03 195阅读 0赞

Java WebSocket是一种在客户端和服务器之间进行全双工、低延迟数据交换的技术。以下是一个简单的WebSocket通信案例,使用Spring Boot框架:

  1. 创建WebSocket配置类(websocket-config.xml):
  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:websocket="http://www.springframework.org/schema/websocket"
  3. xsi:schemaLocation="http://www.springframework.org/schema/beans
  4. http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
  5. http://www.springframework.org/schema/websocket
  6. http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd">
  7. <!-- 配置WebSocket端点 -->
  8. <websocket:serverEndpoint id="chatServer" path="/chat"/>
  9. </beans>
  1. 创建WebSocket客户端(ChatClient.java):
  1. import org.springframework.web.socket.TextMessage;
  2. import org.springframework.web.socket.WebSocketSession;
  3. public class ChatClient {
  4. private WebSocketSession session;
  5. public void connect(String uri) {
  6. // 使用Spring Boot的WebSocket配置类创建连接
  7. session = WebSocketTemplate.getWebSocket_session(uri);
  8. if (session != null) {
  9. session.getAsyncRemote().sendText("Hello from client!");
  10. } else {
  11. System.out.println("Failed to connect to server.");
  12. }
  13. }
  14. public void sendMessage(String message) {
  15. if (session != null) {
  16. TextMessage textMsg = new TextMessage(message);
  17. session.getAsyncRemote().send(textMsg);
  18. } else {
  19. System.out.println("Session not found, cannot send message.");
  20. }
  21. }
  22. public WebSocketSession getSession() {
  23. return session;
  24. }
  25. public void disconnect() {
  26. if (session != null) {
  27. session.close();
  28. System.out.println("Disconnected from server successfully.");
  29. } else {
  30. System.out.println("Session not found, cannot disconnect.");
  31. }
  32. }
  33. }
  1. 创建WebSocket服务端(ChatServer.java):
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.socket.TextMessage;
  4. import org.springframework.web.socket.WebSocketSession;
  5. import org.springframework.web.socket.server.SessionHandler;
  6. import org.springframework.web.socket.server.TextWebSocketSession;
  7. @Configuration
  8. public class ChatServer {
  9. @Bean
  10. public SessionHandler sessionHandler() {
  11. return new TextWebSocketSession();
  12. }
  13. }

现在,你有了一个基本的WebSocket客户端和服务器端。客户端通过连接到特定路径的方式发送消息,服务器端接收到消息后返回响应。

请根据实际需求修改代码,例如添加认证、处理复杂消息等功能。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,195人围观)

还没有评论,来说两句吧...

相关阅读