Socket.io server doesn't seem to get a connection?
I'm working my way through the tutorials on NodeTuts. I'm trying to get a chat server working using socket.io.
I can start the node instance fine and I get the "socket.io ready - accepting connections" message when I do. When I point my browser at localhost:8888 I get served the html form from template.html also so that all looks good. I never seem to make a socket connection though and I never see the "Connection Received" log or the 'Welcome to the chat server' message.
Any ideas what the problem is?
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);
Here's the JS part of 开发者_如何学Gotemplate.html
<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>
I believe you need to call socket.connect();
in your client-side code, right after socket = new io.Socket('localhost', {port: 8888});
精彩评论