Socket.io: Connection closed before receiving a handshake response

为君一笑 提交于 2019-12-25 04:57:22

问题


I decided to make a chat on socket.io, so I just copied an example from http://psitsmike.com/2011/09/node-js-and-socket-io-chat-tutorial/.

Server side:

var app = require('express').createServer()
var io = require('socket.io').listen(app);
app.listen(8080);

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/index.html');
});

var usernames = {};

io.sockets.on('connection', function(socket) {
    socket.on('sendchat', function(data) {
        io.sockets.emit('updatechat', socket.username, data);
    });

    socket.on('adduser', function(username) {
        socket.username = username;
        usernames[username] = username;
        socket.emit('updatechat', 'SERVER', 'you have connected');
        socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
        io.sockets.emit('updateusers', usernames);
    });

    socket.on('disconnect', function() {
        delete usernames[socket.username];
        io.sockets.emit('updateusers', usernames);
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
    });
});

Client side:

< script src="/socket.io/socket.io.js">< /script>
< script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></ script>
< script>
var socket = io.connect('http://localhost:8080');
...

The script works fine but I found out in the Chrome console that it can't establish a websocket connection, and falls back to XHR ('websocket connection invalid'). Tried to change ports, and also tested both on localhost and VPS - same results. What can be the reason? Using express 2.4.6 and socket.io 0.8.4.


回答1:


Application is deployed as part of same container view , it will automatically connect using application url . Host and port might not be required , check with below options

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>

Other option

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://localhost');     
</script>


来源:https://stackoverflow.com/questions/37209713/socket-io-connection-closed-before-receiving-a-handshake-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!