【发布时间】:2011-10-09 20:58:27
【问题描述】:
我是 Socket.IO 的 100% 新手,并且刚刚安装了它。 我试图遵循一些示例,并且可以让服务器端运行,但我似乎无法连接客户端。
以下是我的server.js:
var http = require('http'), io = require('socket.io'),
server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello world</h1>');
});
server.listen(8090);
var socket = io.listen(server);
socket.on('connection', function(client){
console.log('Client connected.');
client.on('message', function(){
console.log('Message.');
client.send('Lorem ipsum dolor sit amet');
});
client.on('disconnect', function(){
console.log('Disconnected.');
});
});
这是我的 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Socket Example</title>
<base href="/" />
<meta charset="UTF-8" />
<script src="http://localhost:8090/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
</head><body>
<script type="text/javascript">
$(document).ready(function(){
var socket = new io.Socket('localhost', { 'port': 8090 });
socket.connect();
console.log("Connecting.");
socket.on('connect', function () {
console.log("Connected.");
});
socket.on('message', function (msg) {
console.log("Message: " + msg + ".");
});
socket.on('disconnect', function () {
console.log("Disconnected.");
});
});
</script>
</body></html>
当我执行 node server.js 时,它表明 socket.io 已启动。
当我加载 index.html 时,出现一行指示“调试 - 提供静态 /socket.io.js” 但仅此而已,没有控制台消息或其他行。
非常感谢您提供的任何指导。正如我所说,我对此表示 100% 的支持,所以如果你能尽可能地分解它,我也将不胜感激。
谢谢
【问题讨论】:
-
您的 index.html 的 URL 位置是什么?如果它不是以“localhost:8090”开头的,浏览器会因为违反同源策略而阻止你连接服务器。
-
那么如何构建他们的文件以便能够在网页上执行一个简单的聊天脚本......比如......你如何在网络服务器上获得domain.com/index.html 指向域。 com:8090/index.html 等
-
errr... 所以 index.html 实际上在 domain.com:8090/index.html 上?
-
它位于 localhost/Test/index.html(就像 localhost/Test/server.js 是服务器 javascript)。我只是想找出构建文件并使其连接的最佳方法。当我访问 localhost:8090 时,我得到了 Hello World。但是当我尝试访问 localhost:8090/index.html 或通过标准 :80 端口地址时什么也没有。
标签: javascript node.js socket.io