Socket.IO基本示例不起作用

我是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> 

当我做节点server.js它表明socket.io已启动。

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

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

谢谢

在同一个源策略中 , localhost:8090localhost不是同一个来源(不同的端口),所以localhost/index.html不能连接到localhost:8090上的socket.io。

一个select是在localhost:8090上创buildindex.html(见下面的代码)。 然后,只需将“index.html”放入服务器脚本的同一目录中,启动服务器并在浏览器中inputlocalhost: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); } }); });