当前位置:   article > 正文

nginx配置websocket连接

nginx配置websocker连接

1.vue中配置websocket连接

data中添加属性

socket: null,

配置websocket连接信息

  1. if (typeof (WebSocket) === 'undefined') {
  2. this.$message({
  3. message: '您的浏览器不支持socket',
  4. type: 'error'
  5. })
  6. } else {
  7. // 实例化socket
  8. this.socket = new WebSocket('ws://10.111.106.73:80//ws/webSocketServer.do')
  9. // 监听socket连接
  10. this.socket.onopen = this.openSocket
  11. // 监听socket错误信息
  12. this.socket.onerror = this.errorSocket
  13. // 监听socket消息
  14. this.socket.onmessage = this.getMessageSocket
  15. // 关闭socket消息
  16. this.socket.onclose = this.closeSocket
  17. }

配置连接打开关闭和获取信息的方法

  1. openSocket() {
  2. console.log('已建立链接')
  3. },
  4. errorSocket() {
  5. console.log('建立链接失败')
  6. },
  7. getMessageSocket(res) {
  8. // 接收到信息
  9. },
  10. sendSocket() {
  11. // this.socket.send('建立链接')
  12. },
  13. closeSocket() {
  14. console.log('链接已断开')
  15. },

2.nginx配置websocket连接

  1. server {
  2. listen 80;
  3. server_name localhost;
  4. add_header Set-Cookie "XAuthorization=$arg_token";
  5. add_header Set-Cookie "Authorization=$http_authorization";
  6. location ~* \.(html|htm|js|css|png|gif|jpg|jpej|rar|zip|svg|json)$ {
  7. root html;
  8. index index.html index.htm;
  9. }
  10. location /ws/ {
  11. proxy_pass http://localhost:8070/; #通过配置端口指向部署websocker的项目
  12. proxy_http_version 1.1;
  13. proxy_set_header Upgrade $http_upgrade;
  14. proxy_set_header Connection "Upgrade";
  15. proxy_set_header X-real-ip $remote_addr;
  16. proxy_set_header X-Forwarded-For $remote_addr;
  17. }
  18. client_max_body_size 100m;
  19. }

3.spring boot后台配置websocekt连接

配置类

  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
  3. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  5. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  6. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  7. import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
  8. /**
  9. * @author wenyoulong
  10. */
  11. @Configuration
  12. @EnableWebSocket
  13. @EnableWebMvc
  14. public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
  15. @Override
  16. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  17. registry.addHandler(new SystemWebSocketHandler(), "/webSocketServer.do").addInterceptors(new WebSocketInterceptor()).setAllowedOrigins("*");
  18. }
  19. @Override
  20. public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  21. configurer.enable();
  22. }
  23. }

拦截器

  1. import org.springframework.http.server.ServerHttpRequest;
  2. import org.springframework.http.server.ServerHttpResponse;
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.web.socket.WebSocketHandler;
  5. import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
  6. import java.util.Map;
  7. /**
  8. * @author wenyoulong
  9. */
  10. @Component
  11. public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {
  12. @Override
  13. public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
  14. Map<String, Object> attributes) throws Exception {
  15. System.out.println("握手前");
  16. if(request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
  17. request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
  18. }
  19. return true;
  20. }
  21. @Override
  22. public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
  23. super.afterHandshake(request, response, wsHandler, ex);
  24. }
  25. }

websocket处理业务

  1. import org.springframework.stereotype.Component;
  2. import org.springframework.web.socket.*;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. /**
  7. * @author wenyoulong
  8. */
  9. @Component
  10. public class SystemWebSocketHandler implements WebSocketHandler {
  11. private static List<WebSocketSession> socketSessions = new ArrayList<>();
  12. @Override
  13. public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
  14. socketSessions.remove(session);
  15. }
  16. @Override
  17. public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
  18. }
  19. @Override
  20. public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
  21. if (message instanceof TextMessage) {
  22. handlerTextMessage(session, (TextMessage) message);
  23. }
  24. }
  25. @Override
  26. public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  27. System.out.println("连接建立");
  28. socketSessions.add(session);
  29. }
  30. @Override
  31. public boolean supportsPartialMessages() {
  32. return false;
  33. }
  34. /**
  35. * 处理文本消息
  36. *
  37. * @throws IOException
  38. **/
  39. private void handlerTextMessage(WebSocketSession session, TextMessage message) throws IOException {
  40. String payLoad = message.getPayload();
  41. System.out.println("接受的消息:"+payLoad);
  42. }
  43. /**
  44. * 给所有在线用户发送消息
  45. *
  46. * @param message
  47. */
  48. public void sendMessageToUsers(TextMessage message) {
  49. try {
  50. for(WebSocketSession socketSession:socketSessions){
  51. socketSession.sendMessage(message);
  52. }
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. }

这样就可以连接了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/733231
推荐阅读
相关标签
  

闽ICP备14008679号