2015-09-27 78 views
7

我想用node.js創建類似char的東西 我是nodejs的新手,我想在沒有socket.io的情況下創建它(我想了解它是如何工作的)。 這是我使用的代碼。node js net sockets + websocket without socket.io

var http = require('http'); 
var net = require('net'); 


var server = http.createServer(function(req,res){ 

    res.writeHead(200,{'content-type' : 'text/html'}); 
    res.write('<a href="./lol/">lol</a><br>'); 
    res.end('hello world: '+req.url); 



    var client = new net.Socket(); 
    client.connect('7001', '127.0.0.1', function() { 

     console.log('CONNECTED TO: '); 
     // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
     client.write('I am Chuck Norris!'); 

    }); 

    // Add a 'data' event handler for the client socket 
    // data is what the server sent to this socket 
    client.on('data', function(data) { 

     console.log('DATA: ' + data); 
     // Close the client socket completely 
     client.destroy(); 

    }); 

    // Add a 'close' event handler for the client socket 
    client.on('close', function() { 
     console.log('Connection closed'); 
    }); 
    //req. 

}); 
server.listen(7000); 


require('net').createServer(function (socket) { 
    console.log("connected"); 

    socket.on('data', function (data) { 
     console.log(data.toString()); 
    }); 
}).listen(7001); 

而且一切正常,(我認爲)。 當我打開本地主機:7000我收到有關「連接到:」和「連接」和「我是查克諾里斯」的節點CMD消息。 後,我在瀏覽器控制檯嘗試寫:

var conn = new WebSocket('ws://localhost:7001/'); 

而且沒有錯誤,但是當我試圖這樣一行:

conn.send('lol'); 

我得到錯誤:「未捕獲拋出:DOMException:失敗在'WebSocket'上執行'發送':仍處於連接狀態(...)「

並且經過一段時間後,我又收到一個錯誤:」WebSocket連接到'ws:// localhost:7001 /'失敗:WebSocket打開握手超時「

也許這個代碼是錯誤的,但我已經嘗試了所有我發現拋出谷歌。有人可以幫我弄這個嗎?

+0

WebSocket協議比打開一個端口複雜得多。如果你想要這個工作,你必須在服務器端實現握手和成幀。查看'ws'庫,也許。 –

回答

8

如果您想創建自己的webSocket服務器,可以從瀏覽器接收webSocket連接,則必須在服務器上實現webSocket協議。它不僅僅是一個簡單的套接字連接。它有一個啓動順序,首先作爲HTTP連接,然後「升級」到webSocket協議,包括交換安全信息,然後通過webSocket發送所有數據的webSocket成幀格式。您不只是通過webSocket發送純文本。

你可以在這裏看到webSocket協議的樣子:Writing Websocket Servers。除非你真的想讓自己的webSocket服務器僅用於學習目的,否則我真的建議你得到一個已經完成了所有基本協議的模塊。

然後,socket.io庫建立在webSocket協議的基礎上,在其上增加了額外的功能和消息格式。

爲了給你一個想法的WebSocket如何連接,這裏是一個典型的連接順序:

瀏覽器發送連接請求:

GET /chat HTTP/1.1 
Host: example.com:8000 
Upgrade: websocket 
Connection: Upgrade 
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== 
Sec-WebSocket-Version: 13 

服務器響應:

HTTP/1.1 101 Switching Protocols 
Upgrade: websocket 
Connection: Upgrade 
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= 

之後,雙方切換到具有如下數據成幀格式的webSocket協議:

0     1     2     3 
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
+-+-+-+-+-------+-+-------------+-------------------------------+ 
|F|R|R|R| opcode|M| Payload len | Extended payload length | 
|I|S|S|S| (4) |A|  (7)  |    (16/64)   | 
|N|V|V|V|  |S|    | (if payload len==126/127) | 
| |1|2|3|  |K|    |        | 
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + 
|  Extended payload length continued, if payload len == 127 | 
+ - - - - - - - - - - - - - - - +-------------------------------+ 
|        |Masking-key, if MASK set to 1 | 
+-------------------------------+-------------------------------+ 
| Masking-key (continued)  |   Payload Data   | 
+-------------------------------- - - - - - - - - - - - - - - - + 
:      Payload Data continued ...    : 
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + 
|      Payload Data continued ...    | 
+---------------------------------------------------------------+ 

然後,此外,還有用於保持活動測試的ping和pong數據包,並且存在用於大數據包和碎片的方案,並且客戶端/服務器可以協商子協議。

+0

謝謝!這非常有幫助! –

+0

謝謝@ jfriend00,我在nodejs net模塊和http升級之間花了很多時間以避免使用第三方庫,您的回答讓我相信現在停下來,並開始使用ready套接字庫,謝謝。 –