1.引入pomgroupId>tomcat-embed-websocket2、配置webSocket类...{返回新的ServerEndpointExporter();}}3.写webSocket服务@ServerEndpoint(value="/api/applet/websocket")@ComponentpublicclassAppletWebSocket{/***静态变量为记录当前在线连接数*/privatevolatilestaticintonlineCount=0;/***concurrent包的线程安全的Set用于存放每个client对应的MyWebSocket对象*/privatevolatilestaticCopyOnWriteArraySetwebSocketSet=newCopyOnWriteArraySet();/***与客户端的连接会话需要通过它向客户端发送数据*/privateSessionsession;/***用户ID*/privateLonguserId;/***连接建立成功时调用的方法*每次创建新链接,查询用户状态*/@OnOpenpublicvoidonOpen(Sessionsession,@PathParam("token")Stringtoken)抛出IOException,EncodeException{this.session=session;webSocketSet.add(this);添加在线计数();}/***连接关闭时调用的方法*/@OnClosepublicvoidonClose(){webSocketSet.remove(this);subOnlineCount();}/***收到客户端消息后调用的方法**@parammessage客户端发送的消息*/@OnMessagepublicvoidonMessage(Stringmessage,Sessionsession){try{sendMessage(message));}catch(IOExceptione){System.out.println(e);}}/***发生错误时调用*/@OnErrorpublicvoidonError(Sessionsession,Throwableerror){System.out.println("发生错误");错误.printStackTrace();}publicvoidsendMessage(Stringmessage)throwsIOException{this.session.getBasicRemote().sendText(message);}/***群发自定义消息*/publicstaticvoidsendInfo(Stringmessage)throwsIOException{for(AppletWebSocketitem:webSocketSet){try{item.sendMessage(message);}catch(IOExceptione){继续;}}}publicstaticsynchronizedintgetOnlineCount(){returnonlineCount;}publicstaticsynchronizedvoidaddOnlineCount(){AppletWebSocket.onlineCount++;}publicstaticsynchronizedvoidsubOnlineCount(){AppletWebSocket.onlineCount--;}publicCopyOnWriteArraySetgetWebSocketSet(){返回webSocketSet;}浦blicLonggetUserId(){返回userId;}publicSessiongetSession(){返回会话;}}4.测试界面是否正常打开在线测试网址:http://coolaf.com/tool/chattest输入自己的服务地址,记住如果url以ws://开头,可以自己引用测试正常的程序,具体以业务规则为准。可以启动多个套接字服务。6.遇到的坑1)本地可以正常连接,向服务器发帖显示404,请按以下情况检查:nginx配置检查位置/websocket/applet{#websocket配置proxy_connect_timeout4s;proxy_read_timeout7200秒;#超过7200秒(两小时proxy_send_timeout12s;proxy_set_headerUpgrade$http_upgrade;proxy_set_headerConnection"upgrade";proxy_passhttp://localhost:8587/websocket/applet;}b.请ping一下你的域名是否指向你的serveripaddresswin+R打开dos窗口ping你的域名,我的就是这样,一直报404,但是我的其他界面没问题,查看后发现我的www.51bishe.site使用CDN加速,指向加速后的地址,导致一致报404,如果使用域名不行,可以使用ip地址测试,缩小排查范围。c.如果你的服务器使用https加密协议,记住你的socket请求地址以wss://开头,本文由博客多发平台OpenWrite发布!