问题
I'm writing a websocket server using node.js and express, and I use the express-ws middleware to help me. But the client can't connect the server.Below is my code.
app.js:
var app = express();
var expressWs = require("express-ws")(app);
...
var webso = require("./routes/ws");
app.use("/chat",webso);
routes/ws.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;
the client:
wx.connectSocket({
url:"ws://localhost:3000/chat",
success(){
console.log("success")
},
fail(){
console.log("err")
},
complete(){
console.log("done");
}
});
the client can't connect the websocket server:
asdebug.js:1 WebSocket connection to 'ws://localhost:3000/chat' failed: Connection closed before receiving a handshake response
I think something wrong I has made at the express server.I need your help.
回答1:
Are you doing an app.listen(3000) in app.js to open that port?
Websockets are just an upgrade to HTTP(s) so you can run on the same port as the rest of your routes.
Your server-side code is fine by the looks of it - not sure about client-side though. This works fine and outputs 'socket from client' when opened:
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);
ws.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>
来源:https://stackoverflow.com/questions/40438048/cant-create-a-websocket-sever-correctly-by-express-ws-middleware