2011-07-21 40 views
2

我是Socket.IO的100%新手,并且已经安装了它。 我试图遵循一些例子,并可以让服务器端运行,但我似乎无法获得客户端连接。Socket.IO基本示例不能正常工作

以下是我的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> 

当我做节点server.js表明socket.io开始。

当我加载index.html时出现一条线指示“调试 - 服务静态/socket.io.js” 但没有别的,没有控制台消息或其他线路。

任何你可以提供的指导将非常感激。正如我所说,我100%的绿色,所以如果你可以尽可能地分解它,我也会很感激。

由于

+0

什么是index.html的URL位置?如果它不以“http:// localhost:8090 /”开头,浏览器将阻止您连接到服务器,因为它违反了相同的源策略。 – Ghostoy

+0

那么如何构建他们的文件可以说在网页上做一个简单的聊天脚本..就像..如何在Web服务器上,你是否http://domain.com/index.html指向域.com:8090/index.html等 –

+0

errr ...所以index.html实际上是在http://domain.com:8090/index.html? – Ghostoy

回答

3

same origin policylocalhost:8090localhost不是相同的起源(不同的端口),所以localhost/index.html不能连接到socket.io在localhost:8090。

一种选择是在localhost:8090上制作index.html(见下面的代码)。然后,只需将“index.html”放入服务器脚本的同一目录中,启动服务器并在浏览器中输入localhost:8090

var fs = require('fs'); 

server = http.createServer(function(req, res){ 
    fs.readFile(__dirname + '/index.html', 'utf-8', function(err, data) { // read index.html in local file system 
     if (err) { 
      res.writeHead(404, {'Content-Type': 'text/html'}); 
      res.end('<h1>Page Not Found</h1>'); 
     } else { 
      res.writeHead(200, {'Content-Type': 'text/html'}); 
      res.end(data); 
     } 
    }); 
});