2013-09-28 53 views
1

我是新來的HTML5和node.js。我正在嘗試創建一個非常基本的客戶端 - 服務器應用程序。這是代碼。使用websockets和node.js的Web應用程序

服務器端(node.js中):

var net = require('net'); 

var server = net.createServer(function(c) { 

    console.log('client connected'); 
    c.setEncoding('utf8'); 

    c.on('end', function() { 
     console.log('client disconnected'); 
    }); 

    c.on('data', function(data) { 
     console.log(data); 
     c.write("Got it"); 
    }); 

}); 

server.listen(9998); 

客戶端(網頁套接字):

<!DOCTYPE html> 

<html> 
    <head> 
     <script> 

      try { 

       var ws = new WebSocket('ws://127.0.0.1:9998'); 

       ws.onopen = function() { 
        ws.send("Message to send"); 
        alert("Message is sent..."); 
       }; 

       ws.onmessage = function (evt) { 
        var message = evt.data; 
        alert("Message is received: " + message); 
       }; 

       ws.onclose = function() { 
        alert("Connection is closed..."); 
       }; 

      } catch (err) { 
       alert(err.message); 
      } 

     </script> 
    </head> 
    <body> 
    </body> 
</html> 

據我瞭解,客戶端應該連接到服務器,發送「告發送「,服務器應該回答」Got it「。相反,服務器接收的是客戶端html頁面的http GET請求,並且沒有任何客戶端回調會被觸發。我錯過了什麼?

回答

0

你錯過了WebSocket,它的TCP但不是原始的TCP,建立一個連接,客戶端必須先發送一個HTTP請求,然後服務器將協議切換到websockets,但記住websocket不是原始的TCP,那裏是數據包和其他的自定義標題。

爲了節省您的一些時間,請嘗試使用https://github.com/LearnBoost/Socket.IO/或其他websocket庫https://github.com/joyent/node/wiki/Modules

+0

謝謝您的信息。 –

相關問題