我正在学习NodeTuts的教程。我正在尝试使用socket.io.让聊天服务器正常工作
我可以很好地启动节点实例,当我这样做时,我会收到"socket.io ready-acceptang connections"消息。当我将浏览器指向localhost:8888时,我也会收到template.html的html表单,这样一切看起来都很好。不过,我似乎从未进行过套接字连接,也从未看到"收到连接"日志或"欢迎使用聊天服务器"消息。
你知道问题出在哪里吗?
var fs, http, io, server, socket, sys;
http = require('http');
fs = require('fs');
sys = require('sys');
io = require('socket.io');
server = http.createServer(function(req, res) {
var rs;
console.log('server started');
res.writeHead(200, {
'Content-Type': 'text/html'
});
rs = fs.createReadStream(__dirname + '/template.html');
return sys.pump(rs, res);
});
socket = io.listen(server);
socket.on('connection', function(client) {
var username;
console.log('Connection received');
client.send('Welcome to the chat server');
client.send('Please enter a username');
return client.on('message', function(message) {
if (!username) {
username = message;
return client.send("Hi " + username + "!");
} else {
return socket.broadcast("" + username + ": " + message);
}
});
});
server.listen(8888);
以下是template.html 的JS部分
<script src="/socket.io/socket.io.js"></script>
<script>
$(function() {
socket = new io.Socket('localhost', {port: 8888});
socket.on('message', function(message) {
var data = message.data
data = data.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
console.log( data );
$('#log ul').append('<li>' + data + '</li>');
window.scrollBy(0, 1000000000000000);
entry_el.focus();
});
var entry_el = $('#entry');
entry_el.keypress(function(event) {
if (event.keyCode != 13) return;
var msg = entry_el.attr('value');
// if the message is not empty
if (msg) {
socket.send(msg);
entry_el.attr('value', '');
}
});
});
</script>
我认为您需要在客户端代码中调用socket.connect();
,就在socket = new io.Socket('localhost', {port: 8888});
之后