我正在使用node.js和express编写一个websocket服务器,我使用express-ws中间件来帮助我。但是客户端无法连接服务器。下面是我的代码。
app.js:
var app = express();
var expressWs = require("express-ws")(app);
...
var webso = require("./routes/ws");
app.use("/chat",webso);
路线/js:
var express = require('express');
var router = express.Router();
router.ws("/",function(ws,req){
console.log("socket from client")
ws.on('message',function(msg){
ws.send('back from node');
})
});
module.exports=router;
客户端:wx.connectSocket({
url:"ws://localhost:3000/chat",
success(){
console.log("success")
},
fail(){
console.log("err")
},
complete(){
console.log("done");
}
});
客户端无法连接websocket服务器:
asdebug.js:1 WebSocket connection to 'ws://localhost:3000/chat' failed: Connection closed before receiving a handshake response
我想我在快递服务上做错了什么。我需要你的帮助。
您是否在app.js中做app.listen(3000)
以打开该端口?Websockets只是HTTP(s)的升级,这样你就可以在与其他路由相同的端口上运行。
你的服务器端代码看起来很好,但不确定客户端。这工作得很好,当打开时输出'socket from client':
app.js
var express = require('express');
var app = express();
var expressWs = require("express-ws")(app);
var webso = require("./ws.js");
app.use("/chat",webso);
app.listen(3000);
js
var express = require('express');
var router = express.Router();
router.ws("/",function(ws,req){
console.log("socket from client")
ws.on('message',function(msg){
ws.send('back from node');
})
});
module.exports=router;
test.htm
<script type="text/javascript">
websocket = new WebSocket('ws://localhost:3000/chat');
</script>