简体   繁体   English

如何实现请求-使用套接字的响应逻辑

[英]How to implement Request – response logic using socket

HTTP HttpRequest(json) .then(result=> console.log(result)) .catch(error => console.error(error)) HTTP HttpRequest(json).then(结果=> console.log(结果)).catch(错误=> console.error(错误))

But, if you use socket 但是,如果您使用套接字

socket.send (json) - in one place code socket.send(json)-一个地方的代码

socket.on (message) - elsewhere in the code socket.on(消息)-代码中的其他地方

I want to do so: socketRequest(json) .then(result=> console.log(result)) .catch(error => console.error(error)) 我想这样做:socketRequest(json).then(result => console.log(result)).catch(error => console.error(error))

It's all about programming the socketRequest module) 全部与对socketRequest模块进行编程有关)

It's all about your protocol design. 这一切都与您的协议设计有关。

Sockets are designed to emulate how serial interfaces work - data come in 8 bits at a time and... nothing else. 套接字被设计为模拟串行接口的工作方式-数据一次输入8位,而其他...。 Sockets have no concept of messages - just bytes. 套接字没有消息的概念,只有字节。 Think of sockets as a USB keyboard. 将插座视为USB键盘。 Your software only get bytes as users type one letter at a time (sometimes your software get groups of bytes if the user types fast enough or keep pressing a key). 当用户一次键入一个字母时,您的软件仅获得字节(有时,如果用户键入得足够快或按住某个键,则您的软件将获得字节组)。 You need to decide what makes a "packet". 您需要确定什么构成“数据包”。 A sentence? 一句话? Then your software should detect full stops "." 然后,您的软件应检测到句号"." . A line? 一条线? Then you detect newlines. 然后,您检测到换行符。

The following is a simple example of an HTTP 1.0 client (the main difference is that HTTP 1.0 signals end of packet by closing the connection while HTTP 1.1 sends a Content-Length header): 以下是HTTP 1.0客户端的一个简单示例(主要区别是HTTP 1.0通过关闭连接而HTTP 1.1发送Content-Length标头来表示分组结束):

function HTTP_1_0_client (url) {
    let urlParts = url.match(/http:..([^/]+)(.*)/);
    let domain = urlParts[1];
    let path = urlParts[2];

    return new Promise((resolve, reject) => {
        let rawString = '';

        const client = net.createConnection(80, domain);
        client.write('GET ' + path + ' HTTP/1.0\n\n');
        client.on('data', buf => rawString += buf.toString());
        client.on('end', () => {
            // headers and body are separated by two newlines:
            let httpParts = rawString.match(/^(.+)\r?\n\r?\n(.*)/);
            let headers = httpParts[1].split(/\r?\n/);
            let text = httpParts[2];

            // first line of response is the status line:
            let statusLine = headers.shift();
            let status = statusLine.match(/^[0-9]+/)[0];

            // return the response to the promise:
            resolve({
                status: status,
                headers: headers,
                responseText: text
            });
        });
        client.on('error', err => reject(err));
    });
}

In the protocol above we simply use socket connection as the end of packet - thus end of response. 在上述协议中,我们仅将套接字连接用作数据包的末尾,即响应的末尾。 You can use other conditions to detect the end of the response cycle and return the response. 您可以使用其他条件来检测响应周期的结束并返回响应。 It all depends on the protocol design. 这完全取决于协议设计。

The following is another simple protocol that simply uses the JSON format to define a packet: 以下是另一种简单的协议,仅使用JSON格式定义数据包:

function JSONclient (host, port, requestData) {
    return new Promise((resolve, reject) => {
        let rawString = '';

        const client = net.createConnection(port, host);
        client.write(JSON.stringify(requestData));
        client.on('data', buf => {
            rawString += buf.toString();

            try {
                let response = JSON.parse(rawString);

                // If we get here it means no errors
                // which means packet is complete -
                // return response to promise:
                resolve(response);

                client.destroy(); // close connection
            }
            catch (err) {
                // Ignore parse error
                // It just means packet isn't complete yet.
            }
        });
        client.on('error', err => reject(err));
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM