Socket Programming

Node.js除了Web上的應用,其針對Socket的支援也相當亮眼... 基於JS語言的特性,在Node.js socket programming中,都是透過on來聆聽事件的event,做出相對應的操作。

下面是個Socket Client的範例:

var net = require('net');

var HOST = 'localost';
var PORT = 22661;

var client = new net.Socket();
/**
 * 使用port與host來設定socket物件
 */
client.connect(PORT, HOST, function() {
  //連線時候訊息與操作
  console.log('CONNECTED TO: ' + HOST + ':' + PORT);
  // 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');
});

Socket Server的部分,是透過原生地net module提供,官方提供的範例如下

var net = require('net');

var server = net.createServer(function (socket) {
  socket.end("goodbye\n");
});

// 未指定port位置,則會動態使用系統可用Port
server.listen(function() {
  address = server.address();
  console.log("opened server on %j", address);
});

測試Socket Server執行:

$ node server.js
opened server on {"address":"0.0.0.0","family":"IPv4","port":51958}

Telnet Client執行:

telnet 127.0.0.1 51958
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
goodbye
Connection closed by foreign host.

results matching ""

    No results matching ""