这个月项目需要用到推送消息的应用,框架上采用websocket,这里记录下所踩的坑,我用的tomcat7+nginx+websocket
一、前端:
1、chrome测试接口的时候,报错failed: Error during WebSocket handshake: Unexpected response code: 404
原因:因为项目中导入了websocket-api.jar
解决:
如果你用的是tomcat7,那么部署的时候要把项目lib目录下的websocket-api.jar删除,因为tomcat已经有这个包了,重复了会报错
如果用tomcat8,重复了无所谓。我弄了半天才发现这两个版本的区别。。所以tomcat7直接引用外部包websocket-api.jar而不是复制到lib目录
2、chrome测试接口的时候,报错:Mixed Content: The page at 'https://www.csdn.net/' was loaded over HTTPS,或者
This request has been blocked; this endpoint must be available over WSS.
解决:不要用https下的网页调试,用http的即可,这点搞了我好久
二、后端
1、后端都简单,注意下url即可
@ServerEndpoint("/websocket/{token}/{username}")
三、附上前端测试的js和nginx配置
1、前端js,直接在chrome下即可测试
var ws = new WebSocket("ws://127.0.0.1:8091/basic/websocket/sdlfdsf3344/user1");
console.log(ws.readyState);
ws.onopen = function(evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!-------------------------------------------");
};
ws.onmessage = function(evt) {
console.log( "Received Message: " + evt.data);
ws.close();
};
ws.onclose = function(evt) {
console.log("Connection closed.");
};
ws.onopen();
2、nginx配置
location /websocket {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://websocket;
}