NodeJS Socket通訊

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   使用   sp   

最近有一部分東西涉及到網路通訊,導師推薦用C語言,自己之前也接觸過。不過突然想到了NodeJS,試用了下,果然NodeJS大法好。

NodeJS的中文版API看這裡:http://nodeapi.ucdok.com/#/api/

 

Socket通訊使用Net模組。

首先,寫服務端部分:

    var net = require(‘net‘);    //create tcp server.    var server = net.createServer(function(socket) {        socket.write(‘hello client!‘);    });        //set listen port.    server.listen(1337, function() {        console.log(‘server listened on port 1337...\r\n‘);    });

require net模組,然後建立server,設定監聽連接埠。這樣就開啟了伺服器。

我們還在建立伺服器的回呼函數裡寫了一條資訊。

 

然後建立用戶端:

    var net = require(‘net‘);    var client = net.connect({         port: 1337,        host: ‘localhost‘    }, function() {        client.write(‘hello server!‘);     });    client.on(‘data‘, function(data) {       console.log(data.toString());    });

同樣包含net模組,建立用戶端,在回呼函數裡也寫了一條資訊。

監聽data事件,接收服務端的資訊。

 

先運行服務端後,在運行用戶端,用戶端就會輸出hello client!。

那麼服務端如何接收用戶端的資訊呢?

 

我們需要讓server監聽 connection事件

    server.on(‘connection‘, function(client) {        client.name = client.remoteAddress + ‘:‘ + client.remotePort;        terminal.on(‘data‘, function(data) {            console.log(‘data from ‘ + client.name + ‘:‘ + data.toString())        });    });

每當有用戶端串連上的時候,查看來源並且列印相應的資訊。

 

實現通訊就是這麼簡單,NodeJS封裝的很好了,具體再查API文檔即可,在通訊中需要將資訊從資料庫讀取或者寫入資料庫,如果使用MySQL,

推薦node-mysql,這篇博文不錯:http://blog.fens.me/nodejs-mysql-intro/

 

其實之前看過node,一直不上手,突然有這個需求,開始看文檔,需求才是動力。

 

NodeJS Socket通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.