idea+spring boot +jdk1.8
1:WebSocket创建
在web项目启动后,启动WebSocket
@Component public class ApplicationInit implements CommandLineRunner, ApplicationListener<ApplicationEvent> { private static Log logger = LogFactory.getLog(ApplicationInit.class); @Override public void run(String... args) { System.out.println("------------------------ Spring初始化完毕 ------------------------"); logger.error("---" + Arrays.toString(args) + "---"); WsPool.startWebsocketInstantMsg(); }
}
2:启动webSocket的方法
/** * 启动websocket */ public static void startWebsocketInstantMsg() { System.out.println("startWebsocketInstantMsg:System"); InetSocketAddress inetSocketAddress = new InetSocketAddress(10000); //端口号 WebSocketImpl.DEBUG = false; MyWebScoket webScoket; webScoket = new MyWebScoket(inetSocketAddress); webScoket.start(); System.out.println("----------websocket启动成功---------------"); InetAddress address = inetSocketAddress.getAddress(); String hostName = inetSocketAddress.getHostName(); int port = inetSocketAddress.getPort(); System.out.println("inetSocketAddress::address==" + address + " hostName==" + hostName + " port==" + port); }
因为wss是要经过证书的,就像https一样,所以要么请求附带证书,要么使用nginx代理(nginx需要已经配置证书)
3:配置nginx代理webSocket
location /websocket{ index index.html index.htm; proxy_pass http://localhost:10010; include proxy.conf; // 其他的通用的代理设置 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; // webSocket需要的独有的头部设置 proxy_set_header Connection “Upgrade”; }
加上:
proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “Upgrade”;
(模拟WebSocket的头部请求信息)
4:请求
http://域名/websocket nginx自动将请求转发到 10000 端口
附:前端连接后端WebSocket触发的方法
/** *建立连接 * * @param conn * @param handshake */ @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { System.out.println("onOpen::连接成功"); // wss连接的时候触发的代码 String openId = handshake.getFieldValue("openId"); //此处可以获取前端传入的参数 this.userJoin(openId, conn); }
/** * 关闭连接 * * @param conn 关闭连接的用户 * @param code 密码 * @param reason 原因 * @param remote 返回远程主机是否启动了连接的关闭。 */ @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { //断开连接时候触发代码 System.out.println("onClose::断开连接"); userLeave(conn); System.out.println(reason); }
/** * 接收到前端的消息 * * @param conn 远程主机(用户) * @param message 消息 */ @Override public void onMessage(WebSocket conn, String message) { System.out.println("接收消息:" + message); JSONObject jsonObject = JsonUtils.parseString(message); }
// 出现异常
@Override public void one rror(WebSocket conn, Exception ex) { //错误时候触发的代码 System.out.println("on error"); ex.printStackTrace(); }