node.js - 如何通过 Node.js net 模块发送 HTTP 响应

标签 node.js

我们的 Node JS 服务器使用 net 模块进行 tcp/ip 通信,是否可以使用 net 模块发送 http 响应?我必须使用http模块来发送http响应吗?

最佳答案

我想添加一些关于使用常规套接字编程发送 HTTP 响应到底需要什么的额外信息。

我一生中至少编写过 4 次 HTTP 服务器(第一次是为了好玩,后来是为了工作),我想向所有有兴趣找出实现符合标准的 HTTP 响应所需的最小努力的人指出 James Marshall 的优秀文章 HTTP Made Really Easy 。该页面自 1998 年以来一直存在,至今仍然是我最喜欢的关于 RFC 2616 (the HTTP spec) 的引用资料之一。真正需要什么以及可以省略什么。

我之前曾在 Node 中编写过自己的 HTTP 服务器,因为我需要 http 模块不提供的自定义处理(或者我只是不知道如何做)。所以这些知识还是有用的。

HTTP 响应的绝对最低要求是:

let server = net.createServer(sock => {
    let client = sock.remoteAddress;
    console.log('serving stream to ' + client);

    // Headers:
    sock.write(
        'HTTP/1.0 200 OK\r\n' +
        '\r\n'
    );

    sock.write('Hello world');
    sock.close(); // HTTP 1.0 signals end of packet by closing the socket
});

server.listen(SOME_PORT);

从这里,您可以按照您想要的任何方式修改代码,以根据需要处理 HTTP 请求。

一般来说,使用 http 模块或更高级别的模块(如 connect)通常更容易。框架或Express.js但了解这个技巧有时会很有帮助。

That one time I wrote my own http server using the net module was because I needed to implement a streaming multipart server so that I can stream an mjpeg video stream. The http module assumes a request/response model which does not fit with the connection/stream model I needed

关于node.js - 如何通过 Node.js net 模块发送 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57352474/

相关文章:

node.js - 如何将 forEach 与 Promises.all 结合起来

node.js - -bash : grunt: command not found

node.js - 是否可以在 ioredis 中使用 hget?

javascript - 网页抓取 - Nightmare js 和请求

jquery - 处理表单发布、nodejs 和 JQueryMobile

node.js - 如何在StrongLoop(LoopBack)中获取Response对象

node.js - 如何在 MongoDB find() 中显示建议

javascript - 为什么我的 for 循环只返回 1 个值

node.js - EINTEGRITY : npm 5. 0 完整性检查和 modernizr.com 依赖

node.js - 是否用于控制台应用程序的 Node 框架