开发者

Socket.io client not connecting with server

I started reading about node.js a few weeks back and decided to learn more about it. I installed node and socket.io and a few other packages (express and some I don't remember) on my Linux server (Turnkey Linux, basically Ubuntu). I found some tutorials and went through them, and couln't get any of the clients to send messages back to the server. Here are some of the tutorials I went through (I have more, but the site wouldn't let me post more links):

Simple chat room http://vivahate.com/2011/03/25/a-simple-chat-room-in-node-js/

Simple Socket.io real-time chat http://webdevrefinery.com/forums/topic/7991-simple-socketio-real-time-chat/

Note that the webdevrefinery one has a live demo on the web, which works in my browser from 2 different computers. There is a link to code which I downloaded and ran, and the server runs just fine. I go to the url (192.168.0.30:3000 on my LAN) and it shows the correct HTML and the console outputs "debug - served static /socket.io.js" as soon as I browse to the URL. When I enter info and it "enter" nothing happens. I put alerts into the code and it seems to fail on the "socket.send" line in "sendMsg()". Here is the code I'm using:

server.js:

    var http = require('http'),
    sys = require('sys'),
    fs = require('fs'),
    io = require('socket.io');

var server = http.createServer(function(req, res) {
    fs.readFile('chat.html', 'binary', function(err, data) {
        if( err ) {
            res.writeHead(500, {'Content-type': 'text/html'});
            res.write(data + "\n");
            res.end();
            return;
        }

        res.writeHead(200, {'Content-type': 'text/html'});
        res.write(data, 'binary');
        res.end();
    });
});
server.listen(3000);

var socket = io.listen(server);
socket.on('connection', function( client ) {
    client.on('message', function(data) {
        console.log("Message: " + JSON.stringify(data));
        socket.broadcast(data);
    });
    client.on('disconnect', function() {
    });
});

client.html

<html>
<head>
<style type="text/css">
#msgs {
    height: 50%;
    overflow-y: scroll;
}

div.odd {
    background-color: gray;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="http://192.168.0.30:3000/socket.io/socket.io.js"></script>
<title>Realtime Chat Test</title>
</head>
<body>
<div id="container">
<div id="msgs"></div>
<div id="form">
<form id="chat" action="javascript:sendMsg()">
Username:<input type="text" name="username" /><br />

Message:<input id="msg" type="text" name="message" /><br />
<input type="submit" />
</form>
</div>
</div>
</body>
<script type="text/javascript">
var socket = new io.Socket("192.168.0.30", {port:3000});
socket.connect();

var classes = new Array('even', 'odd');
var numMsgs = 0;

function reconnect() {
    if( socket.connecting ) {
        setTimeout('reconnect()',1000);
    }
    else if( !socket.connected ) {
        socket.connect();
        setTimeout('reconnect()',1000);
    }
}

socket.on('disconnect', function() {
    reconnect();
});

socket.on('message', function(data) {
    var ms = JSON.parse(data);
    if( ms.username !== undefined && ms.message !== undefined ) {
        numMsgs++;
        $('开发者_运维问答#msgs').append( function() {
            var d = $('<div class="'+classes[numMsgs%2]+'"/>');
            d.text(ms.username + ' says: ' + ms.message);
            return d;
        });
        var objDiv = document.getElementById('msgs');
        objDiv.scrollTop = objDiv.scrollHeight;
    }
}); 

function sendMsg() {
    var values = {};
    $.each($('#chat').serializeArray(), function(i,v) {
        values[v.name] = v.value;
    });
    document.getElementById("msg").value = "";
    socket.send(JSON.stringify(values));
}
</script>
</html>

The distribution of Linux I'm using doesn't have X or anything like that as I do all my browsing from Windows machines, which is why I'm not testing from localhost, although I'm assuming this should work from other hosts as evidenced by the HTML being served and the message being output when I surf to the page. Any ideas on why I never get any messages from the client to the server? I'm assuming I'm making the same mistake with every tutorial as there are about 8 others I've tried but I always have the same issue. Thanks.

Darryl


This is in response to the comments after Alfred's answer. I couldn't figure out how to put another comment in that line so I'm posting an "answer".

@Alfred - thanks for the example, but that does seem like a lot to go though as Daniel said considering I haven't gotten a simple message to go through. @Daniel - As far as the documentation goes I still don't get the idea of how to actually use the example on the socket.io homepage. There's a "How to use" link that does nothing and a Wiki link that doesn't explain anything about the examples. I know how to start the server, but still don't know how to connect the client to the server or even how to "start" the client. Most of the tutorials have some sort of "link code" that points to the client page from the server, then you just point the browser at "http://yoursiteaddress:port" and the page is shown. The code on the socket.io homepage has no "connection" like this between the client and server code. Are you supposed to surf to the "client" code? I tried that and it serves the exact same code no matter what URL I go to assuming I'm going to "http://yoursiteaddress:port" which makes sense, but I haven't seen any documentation actually explaining how to use that code. Hence my going to tutorials which apparently all use old code. Is there some documentation that I'm missing?


I bet you the problem lies in your dependencies. Let's look at my dependencies for example:

$ npm ls

├─┬ express@2.4.3 
│ ├─┬ connect@1.6.0 
│ │ └── qs@0.3.0 
│ ├── mime@1.2.2 
│ └── qs@0.3.0 
├─┬ socket.io@0.7.7 
│ ├── bison@1.1.1  extraneous
│ ├── policyfile@0.0.3 
│ ├── redis@0.6.0 
│ └─┬ socket.io-client@0.7.4 
│   └── uglify-js@1.0.3

From socket.io 0.6.x to 0.7.x the API underwent some major changes. It looks like you are reading old tutorials using socket.io 0.6.x and you have installed 0.7.x. I advice you to read migration instructions.

I like to provide you real simple demo(utilizes express which you have installed) which hopefully does work.

var app = require('express').createServer(),
    sio = require('socket.io');

app.get('/', function(req, res){
  res.send('<script src="/socket.io/socket.io.js"></script>\
<script>\
  var socket = io.connect("http://192.168.0.30");\
  socket.on("news", function (data) {\
    alert(data.hello);\
  });\
</script>');
});

app.listen(3000);

var io = sio.listen(app);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
});

Should alert world when you connect to socket.io server.


What I also think will work with your example is installing socket.io 0.6.18 which is the latest 0.6.x right now inside your directory inside the folder node_modules. Node.js will include that module locally thanks to node.js module system. You can do this by creating that directory if that not already exists issuing mkdir -p node_modules. Next install socket.io issuing npm install socket.io@0.6.18. Then I think you should be able to run those old examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜