2011-07-21 13 views
2

私はSocket.IOを100%新しくしてインストールしました。 私はいくつかの例に従おうとしていて、サーバー側を稼動させることができますが、クライアント側を接続することはできません。私は、ノードが、それはsocket.ioが開始されていることを示しているserver.js行うとこれは私のindex.htmlSocket.IOの基本的な例が動作しない

<!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> 

ある

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.'); 
    }); 

}); 

は私server.jsです。

index.htmlをロードすると、「debug-served static /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 policyにおいて

localhost:8090localhostは同じ起源(異なるポート)ないので、localhost/index.htmlはlocalhostでsocket.ioに接続できません:8090。

1つの方法は、index.htmlをlocalhost:8090(下のコードを参照)にすることです。次に、 "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); 
     } 
    }); 
}); 
関連する問題