美丽的神话 发表于 2024-12-4 23:08:32

学习条记053——实现WebSocket

1、Java原生实现

1.1、导入紧张依靠

<!-- Java原生代码实现websocket依赖 -->
<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.5.3</version>
</dependency>
1.2、继承WebSocketServer

import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

/**
* @author HTL
* @version 2024-7-8008
* @since JDK8
*/
public class SocketServer extends WebSocketServer {

    public SocketServer(int port) throws UnknownHostException {
      super(new InetSocketAddress(port));
    }

    public SocketServer(InetSocketAddress address) {
      super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
      conn.send("Welcome to the server!"); // This method sends a message to the new client
      broadcast("new connection: " + handshake
                .getResourceDescriptor()); // This method sends a message to all clients connected
      System.out.println(
                conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");

    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
      broadcast(conn + " has left the room!");
      System.out.println(conn + " has left the room!");
    }
   

    @Override
    public void onMessage(WebSocket conn, String message) {
      broadcast(message);
      System.out.println(conn + " 发送数据: " + message);
    }


    @Override
    public void onError(WebSocket conn, Exception ex) {
      ex.printStackTrace();
      if (conn != null) {
            // some errors like port binding failed may not be assignable to a specific
            // websocket
      }

    }

    @Override
    public void onStart() {
      System.out.println("Server started!");
      setConnectionLostTimeout(0);
      setConnectionLostTimeout(100);

    }

}

1.3、测试

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* @author HTL
* @version 2024-7-8008
* @since JDK8
*/
public class SocketTest {

    public static void main(String[] args) throws InterruptedException, IOException {
      int port = 8887; // 端口

      SocketServer s = new SocketServer(port);
      s.start();
      System.out.println("ChatServer started on port: " + s.getPort());

      BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
      while (true) {
            String in = sysin.readLine();
            s.broadcast(in);
            if (in.equals("exit")) {
                s.stop(1000);
                break;
            }
      }
    }

}

# 请求地址
ws://127.0.0.1:8887
2、SpringBoot实现

2.1、导入依靠

<!-- 2、SpringBoot实现websocket 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.2、编写配置类

import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
* @author HTL
* @version 2024-7-4004
* @since JDK8
*/
public class WsSessionManager {
    /**
   * 保存连接 session 的地方
   */
    private static ConcurrentHashMap<String, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();

    /**
   * 添加 session
   *
   * @param key
   */
    public static void add(String key, WebSocketSession session) {
      // 添加 session
      SESSION_POOL.put(key, session);
    }

    /**
   * 删除 session,会返回删除的 session
   *
   * @param key
   * @return
   */
    public static WebSocketSession remove(String key) {
      // 删除 session
      return SESSION_POOL.remove(key);
    }

    /**
   * 删除并同步关闭连接
   *
   * @param key
   */
    public static void removeAndClose(String key) {
      WebSocketSession session = remove(key);
      if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                // todo: 关闭出现异常处理
                e.printStackTrace();
            }
      }
    }

    /**
   * 获得 session
   *
   * @param key
   * @return
   */
    public static WebSocketSession get(String key) {
      // 获得 session
      return SESSION_POOL.get(key);
    }
}

继承TextWebSocketHandler
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
* @author HTL
* @version 2024-7-4004
* @since JDK8
*/
@Component
public class HttpAuthHandler extends TextWebSocketHandler {

    /**
   * socket 建立成功事件
   *
   * @param session
   * @throws Exception
   */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
      Object sessionId = session.getAttributes().get("session_id");
      if (sessionId != null) {
            // 用户连接成功,放入在线用户缓存
            WsSessionManager.add(sessionId.toString(), session);
      } else {
            throw new RuntimeException("用户登录已经失效!");
      }
    }

    /**
   * 接收消息事件
   *
   * @param session
   * @param message
   * @throws Exception
   */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
      // 获得客户端传来的消息
      String payload = message.getPayload();
      Object sessionId = session.getAttributes().get("session_id");
      SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      myFormat.format(new Date());
      System.out.println(myFormat.format(new Date()) + " ——> server 接收到:" + sessionId + " 发送的内容:" + payload);
      session.sendMessage(new TextMessage(myFormat.format(new Date()) + " ——> server 返回给:" + sessionId + " 的消息:" + payload));
    }

    /**
   * socket 断开连接时
   *
   * @param session
   * @param status
   * @throws Exception
   */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
      Object sessionId = session.getAttributes().get("session_id");
      if (sessionId != null) {
            // 用户退出,移除缓存
            WsSessionManager.remove(sessionId.toString());
      }
    }


}

实现HandshakeInterceptor
import java.util.Map;

import org.apache.logging.log4j.util.Strings;
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;

/**
* @author HTL
* @version 2024-7-4004
* @since JDK8
*/
@Component
public class MyInterceptor implements HandshakeInterceptor {

    /**
   * 握手前
   */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
      System.out.println("握手开始");
      String hostName = request.getRemoteAddress().getHostName();
      String sessionId = hostName+String.valueOf((int)(Math.random()*1000));
      if (Strings.isNotBlank(sessionId)) {
            // 放入属性域
            attributes.put("session_id", sessionId);
            System.out.println("用户 session_id:" + sessionId + " 握手成功!");
            return true;
      }
      System.out.println("用户登录已失效");
      return false;
    }

    /**
   * 握手后
   */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
      System.out.println("握手完成");
    }

}


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
* @author HTL
* @version 2024-7-4004
* @since JDK8
*/
@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer {

    @Autowired
    private HttpAuthHandler httpAuthHandler;

    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
      registry
                .addHandler(httpAuthHandler, "myWS")//请求地址前缀
                .addInterceptors(myInterceptor)
                .setAllowedOrigins("*");
    }

}


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 学习条记053——实现WebSocket