Socket.io 客户端未与服务器连接
几周前我开始阅读有关 Node.js 的内容,并决定了解更多相关信息。我在我的 Linux 服务器(Turnkey Linux,基本上是 Ubuntu)上安装了 node 和 socket.io 以及其他一些软件包(express 和一些我不记得的)。我找到了一些教程并浏览了它们,但无法让任何客户端将消息发送回服务器。以下是我经历过的一些教程(我有更多,但该网站不允许我发布更多链接):
简单的聊天室 http://vivahate.com/2011/ 03/25/a-simple-chat-room-in-node-js/
简单的Socket.io实时聊天 http://webdevrefinery.com/forums/topic/7991- simple-socketio-real-time-chat/
请注意,webdevrefinery 在网络上有一个实时演示,它可以在我的两台不同计算机的浏览器中运行。有一个指向我下载并运行的代码的链接,服务器运行得很好。我访问该 URL(LAN 上的 192.168.0.30:3000),它显示正确的 HTML,并且一旦我浏览到该 URL,控制台就会输出“debug -served static /socket.io.js”。当我输入信息并且它“输入”时什么也没有发生。我将警报放入代码中,但似乎在“sendMsg()”中的“socket.send”行上失败。这是我正在使用的代码:
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>
我正在使用的 Linux 发行版没有 X 或类似的东西,因为我从 Windows 机器上进行所有浏览,这就是为什么我没有从本地主机进行测试,尽管我假设这应该可以在其他主机上工作,正如我浏览该页面时所提供的 HTML 和输出的消息所证明的那样。关于为什么我从来没有从客户端到服务器收到任何消息有什么想法吗?我假设我在每个教程中都犯了同样的错误,因为我尝试过大约 8 个其他教程,但我总是遇到同样的问题。谢谢。
达里尔
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是对阿尔弗雷德回答后评论的回应。我不知道如何在该行中添加另一条评论,因此我发布了一个“答案”。
@Alfred - 感谢您提供的示例,但正如丹尼尔所说,考虑到我还没有收到简单的消息,这似乎还有很多事情要做。 @Daniel - 就文档而言,我仍然不知道如何实际使用 socket.io 主页上的示例。有一个“如何使用”链接不执行任何操作,还有一个 Wiki 链接不解释有关示例的任何内容。我知道如何启动服务器,但仍然不知道如何将客户端连接到服务器,甚至不知道如何“启动”客户端。大多数教程都有某种从服务器指向客户端页面的“链接代码”,然后您只需将浏览器指向“http://yoursiteaddress:port”即可显示该页面。 socket.io 主页上的代码在客户端和服务器代码之间没有这样的“连接”。您应该浏览“客户端”代码吗?我尝试过,无论我转到哪个 URL,它都会提供完全相同的代码,假设我要访问“http://yoursiteaddress:port”,这是有道理的,但我还没有看到任何文档实际解释如何使用它代码。因此我去的教程显然都使用旧代码。我缺少一些文档吗?
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?
我敢打赌,问题出在你的依赖性上。让我们看看我的依赖项,例如:
从 socket.io 0.6.x 到 0.7.x,API 经历了一些重大变化。看起来您正在阅读使用 socket.io 0.6.x 的旧教程,并且您已经安装了 0.7.x。我建议您阅读迁移说明。
我想为您提供真正简单的演示(利用您已安装的 Express),希望它能起作用。
当您连接到 socket.io 服务器时,应该提醒
world
。我还认为适用于您的示例的是安装socket.io 0.6.18,它是目前在您的文件夹
node_modules
内的目录中的最新版本0.6.x。 Node.js 将在本地包含该模块,这要归功于 node.js 模块系统。如果该目录尚不存在,您可以通过发出mkdir -p node_modules
创建该目录来完成此操作。接下来安装socket.io,发出npm install
[email protected]< /代码>。那么我认为你应该能够运行那些旧的例子。
I bet you the problem lies in your dependencies. Let's look at my dependencies for example:
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.
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 issuingmkdir -p node_modules
. Next install socket.io issuingnpm install [email protected]
. Then I think you should be able to run those old examples.