与 NodeJS 的 TCP/IP 通信以实现多条写入消息 [英] TCP/IP communications with NodeJS for multiple write messages

查看:38
本文介绍了与 NodeJS 的 TCP/IP 通信以实现多条写入消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 TCP/IP 使用 python 构建分布式缓存系统,我已经使用 python 实现了 TCP SERVER,我正在为 Python、PHP 和 NodeJS 创建 TCP 客户端库.

I am working on building a distributed caching system using python over TCP/IP and I have implemented the TCP SERVER using python and I am creating TCP client libraries for Python, PHP and NodeJS.

因此客户端将使用a请求缓存项,TCP服务器将缓存值返回给客户端

So the client will request for a cache item using a and the TCP server will return the cache value back to the client

我遇到了 NodeJS 的问题,因为它是一个基于异步事件的编程工具.

I am facing an issue with NodeJS since it is an Asynchronous event based programming tool.

以下是PHP客户端库的伪代码

Below is the pseudo code for PHP client library

$server = new CacheServer();
$server->connect("<host>", "<port>");
$value_1 = $server->get("<cache_key_1>")
$value_2 = $server->get("<cache_key_2>")

所以 $server->get 方法首先在套接字上写一条消息 e.g.获取"然后在套接字上侦听服务器响应,然后返回该缓存键的值然后才移动到

so what the $server->get method does is first writes a message on the socket e.g. "GET <cache_key_1>" and then listen on the socket for the server to respond and then return the value for that cache key and only then move on to <cache_key_2>

但是对于NodeJS,因为它是基于事件的, 的请求都是在不等待服务器响应的情况下发送的.

But for NodeJS since it was based on event, Both the request for <cache_key_1> and <cache_key_2> are sent without waiting for response from the server.

套接字从服务器读取两个值,但我无法区分哪个值对应哪个请求.我知道 TCP 套接字请求已排队,所以我可能必须像在数组中一样跟踪首先发送的请求,然后获取另一个响应数组,然后映射这些请求.

The sockets reads both the values from server back but I am not able to differentiate which value is for which request. I know TCP socket requests are queued up so may be I have to track which request was sent first like in an array and have another array of responses and then map those.

有没有我看不到的更简单的方法?

Is there a easier way which I am not able to see?

总而言之,我想使用 NodeJS 从 TCP 客户端发送多条写入消息,并在每个写入"消息之间等待来自服务器的响应

In summary I want to send multiple write message from the TCP client using NodeJS and wait for response back from server between each "write" message

任何帮助将不胜感激谢谢!

Any help will be greatly appreciated Thanks!

推荐答案

Idea

当使用套接字处理异步时,想法是用标识符标记请求,并为该标识符注册一个处理程序,当收到响应时,我们与注册的标识符进行匹配.这是因为我们没有将套接字概念化为请求/响应.

When dealing with async using sockets, the idea would be to tag the request with an identifier, and register a handler for that identifier, and when response is received, we match with registered identifiers. This is because we do not conceptualize sockets as request/response.

这是一个示例水库模块 (reservoir.js):

Here is a sample reservoir module (reservoir.js):

var net = require('net');

module.exports = {
    client: {},
    connect: function(port, host, then) {
        var $this = this;
        var client = net.Socket();

        client.connect(port, host, function(){
            then && then();
        });

        client.on("data", function(data) {
            $this._process(data);
        });

        this.client = client;
        return this;
    },
    get: function(key, then) {
        var $this = this;
        $this.client.write(key, function() {
            $this._handle(key, then);
        });
        return this;
    },
    _handlers: {},
    _commands: ['GET', 'SET', 'DEL'],
    _handle: function(key, handler) {
        //remove commands from the key, because server doesn't return them (you can check here if its a valid command)
        var keyParts = key.split(' ');
        keyParts.shift();

        this._handlers[keyParts] = handler;
    },
    _process: function(data) {
        var response = JSON.parse(data.toString());
        var handler = this._handlers[response.incoming_message];
        if (handler) {
            if (response.message) {
                handler(null, response.message);
            } else {
                handler(new Error(response.error), null);
            }
        }
        delete this._handlers[response.incoming_message];
    }
};

这里我们使用关联的键注册每个回调 - 所以当我们收到数据时,我们会启动特定的处理程序.

Here we are registering each callback with the associated key - so when we receive the data, we fire up the specific handler.

在模块文件中的所有抽象之后,这里是如何使用它:

var reservoir = require('reservoir');
var onConnect = function() {
    console.log("\nConnected.");
    reservoir.get('GET pk_movie', function(err, response) {
        console.log(response);
    });
}
reservoir.connect('3000', 'your-host.com', onConnect);

希望有帮助!

这篇关于与 NodeJS 的 TCP/IP 通信以实现多条写入消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆