关于Spring Boot WebSocket整合以及nginx配置详解
前言
本文主要给大家介绍了关于SpringBootWebSocket整合及nginx配置的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
一:SpringBootWebSocket整合
创建一个maven项目,加入如下依赖
org.springframework.boot spring-boot-dependencies 1.4.0.RELEASE import pom org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-websocket
代码如下:
packagecom.wh.web; importorg.springframework.web.socket.TextMessage; importorg.springframework.web.socket.WebSocketSession; importorg.springframework.web.socket.handler.TextWebSocketHandler; publicclassCountWebSocketHandlerextendsTextWebSocketHandler{ privatestaticlongcount=0; protectedvoidhandleTextMessage(WebSocketSessionsession,TextMessagemessage)throwsException{ session.sendMessage(newTextMessage("你是第"+(++count)+"位访客")); } }
packagecom.wh.web; importorg.springframework.context.annotation.Configuration; importorg.springframework.web.socket.config.annotation.WebSocketConfigurer; importorg.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration publicclassWebsocketConfigurationimplementsWebSocketConfigurer{ publicvoidregisterWebSocketHandlers(WebSocketHandlerRegistryregistry){ registry.addHandler(newCountWebSocketHandler(),"/web/count"); } }
packagecom.wh.web; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.web.socket.config.annotation.EnableWebSocket; @EnableWebSocket @SpringBootApplication publicclassServerApp{ publicstaticvoidmain(String[]args){ SpringApplication.run(ServerApp.class,args); } }
application.properties内容如下:
server.port=9080 spring.resources.static-locations=classpath:/webapp/html/
src/main/resources/webapp/html/index.html 内容如下:
websocket websocket
varurl='ws://'+window.location.hostname+':9080/web/count'; varws=newWebSocket(url); ws.onopen=function(event) { ws.send('hello'); }; ws.onmessage=function(event){ alert(event.data); }; ws.onerror=function(event){ alert(event); }
最后,启动main方法,访问http://127.0.0.1:9080/index.html即可看到输出
二:nginx配置
nginx通过在客户端和后端服务器之间建立起一条隧道来支持WebSocket。
为了使nginx可以将来自客户端的Upgrade请求发送给后端服务器,Upgrade和Connection的头信息必须被显式的设置。如下所示:
location/web/count{ proxy_passhttp://tomcat-server; proxy_redirectoff; proxy_http_version1.1; proxy_set_headerUpgrade$http_upgrade; proxy_set_headerConnection"upgrade"; proxy_set_headerHost$host:$server_port; proxy_set_headerX-Real-IP$remote_addr; proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for; }
一旦我们完成以上设置,nginx就可以处理WebSocket连接了。
注意:必须要有 proxy_set_headerHost$host:$server_port; 这个配置
否则,会报:WebSocketconnectionto'ws://192.168.1.104:9080/web/count'failed:ErrorduringWebSockethandshake:Unexpectedresponsecode:403的错误
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。