linux下 据说nginx是要有 stream的模块
Linux安装Nginx步骤之后续,带stream模块-CSDN博客
Nginx从1.3.13版本就开始支持WebSocket
linux 下参考如下链接
配置 Nginx 反向代理 WebSocket - 哈喽哈喽111111 - 博客园 (cnblogs.com)
SSL的配置参考
【Linux】采用nginx反向代理让websocket 支持 wss-CSDN博客
需要确定Nginx是否支持socket
nginx 配置可以参考如下
windows 中我的测试版本是 nginx 1.25.4
nginx 配置文件
完整配置文件
worker_processes 1;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;server {listen 801;server_name localhost;# 自己nginx想暴漏的前缀,随便写location ^~ /wsxxyy {# 这里是 后端java暴漏的完整的socket的路径 socket1 是上下文路径# wsxx 是wesocket的访问路径proxy_pass http://127.0.0.1:10018/socket1/wsxx;proxy_http_version 1.1;proxy_set_header Host $host;# 超时 传输文件大小 根据自己业务添加就行,这个不影响简单socket测通client_max_body_size 300m;proxy_connect_timeout 300s;proxy_send_timeout 300s;proxy_read_timeout 300s;# 下面的必须加proxy_set_header Upgrade "websocket";proxy_set_header Upgrade "upgrade";proxy_set_header Connection "upgrade";}}
}
完整配置文件
java 端代码
maven 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.3.5</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.xxx</groupId><artifactId>socket</artifactId><version>0.0.1-SNAPSHOT</version><name>socket</name><description>socket</description><properties><!-- 不一定用 jdk 22 --><java.version>22</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.32</version><scope>compile</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;@Slf4j
public class WebSocketManager {private final static CopyOnWriteArraySet<WebSocketServer> webSocketServerSet = new CopyOnWriteArraySet<>();private final static ConcurrentHashMap<String, WebSocketServer> webSocketServerMap = new ConcurrentHashMap<>();public static void addWebSocketServer(WebSocketServer webSocketServer){if (webSocketServer != null){webSocketServerSet.add(webSocketServer);webSocketServerMap.put(webSocketServer.getSessionId(), webSocketServer);}}public static void removeWebSocketServer(WebSocketServer webSocketServer){webSocketServerSet.remove(webSocketServer);webSocketServerMap.remove(webSocketServer.getSessionId());}/*** 通过SessionId发送消息给特定用户* @param* @param msg*/public static void sentToUser(String sessionId, String msg){Session session = webSocketServerMap.get(sessionId).getSession();sentToUser(session, msg);}/*** 通过Session发送消息给特定用户* @param session* @param msg*/public static void sentToUser(Session session, String msg){if (session == null){log.error("不存在该Session,无法发送消息");return;}session.getAsyncRemote().sendText(msg);}/*** 发送消息给所有用户* @param msg*/public static void sentToAllUser(String msg){for (WebSocketServer webSocketServer : webSocketServerSet) {sentToUser(webSocketServer.getSession(), msg);}log.info("向所有用户发送WebSocket消息完毕,消息:{}", msg);}
}
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;@Slf4j
@Component
@ServerEndpoint("/wsxx")
public class WebSocketServer {private Session session;@OnOpenpublic void onOpen(Session session) {this.session = session;WebSocketManager.sentToUser(session, "WebSocket is connected!");WebSocketManager.addWebSocketServer(this);log.info("与SessionId:{}建立连接", session.getId());}@OnClosepublic void onClose() {WebSocketManager.removeWebSocketServer(this);log.info("WebSocket连接关闭");}@OnMessagepublic void onMessage(String message, Session session) throws InterruptedException {log.info("来自SessionId:{}的消息:{}", session.getId(), message);while(true){WebSocketManager.sentToUser(session, "服务端接收到你的消息->" + message + "-" + System.currentTimeMillis());Thread.sleep(1000);}}@OnErrorpublic void onError(Session session, Throwable error) {log.error("Session:{}的WebSocket发生错误", session.getId(), error);}public Session getSession() {return session;}public String getSessionId() {return session.getId();}
}
spring:application:name: socket
server:port: 10018servlet:context-path: /socket1