3

PHPのfgetc()関数に相当するNode.jsは何ですか? そして、それをソケットにどのように適用しますか?

私はこのphpスクリプトのnode.jsポートに取り組んでいます: http://code.google.com/p/bf2php/source/browse/trunk/rcon/BF2RConBase.class.php

基本的に、ソケットを使用してバトルフィールド 2 ベースのゲーム サーバーに接続します。私が見ている機能は次のとおりです。

protected function read($bare = false) {
    $delim = $bare ? "\n" : "\x04";
    for($buffer = ''; ($char = fgetc($this->socket)) != $delim; $buffer .= $char);
    return trim($buffer);
}

「\ n」まで一度に1文字ずつ(私が収集したものから)ソケットから直接最初の行を取得することになっています。出力は暗号化ソルトを取得するために使用されると想定しています。この関数は、ログインに必要な暗号化パスワードを生成するコードの一部として、ソケット接続イベントで呼び出されます。この関数に相当する Node.js がどのように見えるかを誰かに教えてもらえますか?

4

1 に答える 1

1

ドキュメントには、ネットワーク経由でサーバーに接続する方法の優れた例があります。

var net = require('net');
var client = net.connect({port: 8124},
    function() { //'connect' listener
  console.log('client connected');
  client.write('world!\r\n');
});
client.on('data', function(data) {
  console.log(data.toString());
  client.end();
});
client.on('end', function() {
  console.log('client disconnected');
});

dataイベント ハンドラを変更して、必要な情報を受け取るまで受信データをバッファするだけです。

そのためには、Buffer.


ストリームからデータをバッファリングし、特定の文字で区切られたメッセージを解析する方法の具体的な例を次に示します。リンクされた PHP で、実装しようとしているプロトコルがメッセージを EOT (0x04) 文字で区切ります。

var net = require('net');


var max = 1024 * 1024 // 1 MB, the maximum amount of data that we will buffer (prevent a bad server from crashing us by filling up RAM)
    , allocate = 4096; // how much memory to allocate at once, 4 kB (there's no point in wasting 1 MB of RAM to buffer a few bytes)
    , buffer=new Buffer(allocate) // create a new buffer that allocates 4 kB to start
    , nread=0 // how many bytes we've buffered so far
    , nproc=0 // how many bytes in the buffer we've processed (to avoid looping over the entire buffer every time data is received)
    , client = net.connect({host:'example.com', port: 8124}); // connect to the server

client.on('data', function(chunk) {
    if (nread + chunk.length > buffer.length) { // if the buffer is too small to hold the data
        var need = Math.min(chunk.length, allocate); // allocate at least 4kB
        if (nread + need > max) throw new Error('Buffer overflow'); // uh-oh, we're all full - TODO you'll want to handle this more gracefully

        var newbuf = new Buffer(buffer.length + need); // because Buffers can't be resized, we must allocate a new one
        buffer.copy(newbuf); // and copy the old one's data to the new one
        buffer = newbuf; // the old, small buffer will be garbage collected
    }

    chunk.copy(buffer, nread); // copy the received chunk of data into the buffer
    nread += chunk.length; // add this chunk's length to the total number of bytes buffered

    pump(); // look at the buffer to see if we've received enough data to act
});

client.on('end', function() {
    // handle disconnect
});


client.on('error', function(err) {
    // handle errors
});


function find(byte) { // look for a specific byte in the buffer
    for (var i = nproc; i < nread; i++) { // look through the buffer, starting from where we left off last time
        if (buffer.readUInt8(i, true) == byte) { // we've found one
            return i;
        }
    }
}
function slice(bytes) { // discard bytes from the beginning of a buffer
    buffer = buffer.slice(bytes); // slice off the bytes
    nread -= bytes; // note that we've removed bytes
    nproc = 0; // and reset the processed bytes counter
}

function pump() {
    var pos; // position of a EOT character

    while ((pos = find(0x04)) >= 0) { // keep going while there's a EOT (0x04) somewhere in the buffer
        if (pos == 0) { // if there's more than one EOT in a row, the buffer will now start with a EOT
            slice(1); // discard it
            continue; // so that the next iteration will start with data
        }
        process(buffer.slice(0,pos)); // hand off the message
        slice(pos+1); // and slice the processed data off the buffer
    }
}

function process(msg) { // here's where we do something with a message
    if (msg.length > 0) { // ignore empty messages
        // here's where you have to decide what to do with the data you've received
        // experiment with the protocol
    }
}

完全にテストされていないため、エラーが発生する可能性があります。ここで収集する主な点は、データが到着したら、それをメモリにバッファリングすることです。バッファ内で区切り文字を見つけたら、メッセージを処理できます。

于 2012-10-08T20:53:50.807 に答える