我决定在socket.io上聊聊,所以我只是从http://psitsmike.com/2011/09/node-js-and-socket-io-chat-tutorial/复制了一个例子。
服务器端:
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');
});
});
客户方:
< 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');
...
该脚本运行正常,但我在Chrome控制台中发现它无法建立websocket连接,并且回退到XHR('websocket connection invalid')。尝试更改端口,并在localhost和VPS上测试 - 相同的结果。可能是什么原因?使用express 2.4.6和socket.io 0.8.4。
答案 0 :(得分:0)
应用程序部署为同一容器视图的一部分,它将使用应用程序URL自动连接。可能不需要主机和端口,请查看以下选项
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
其他选项
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
</script>