server
var io = require('socket.io')();
io.on('connection', function(socket) {
//接受消息
socket.on('message', function (msg) {
console.log('receive messge : ' + msg );
});
//发送消息
socket.emit('message', 'hello');
//断开连接回调
socket.on('disconnect', function () {
console.log('socket disconnect');
});
});
io.listen(3000);
client
<script>
window.onload = function () {
var ws = new WebSocket('ws://localhost:3000');
ws.onopen = function (e) {
console.log("连接服务器成功");
ws.send("1");
}
}
</script>
报错
index.html:14 WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
请问这是为什么呢? 如何解决呢?
尝试了一下直接这么写确实会有问题。
是这样的。你服务端用了socket.io这个包。
你客户端也得配套的使用socket.io-client这个包。
例如:
点我访问socket.io-client的github