Nodejs 求助:http.request一个socketPath的情况

Nodejs 求助:http.request一个socketPath的情况

如下两段代码:

http = require 'http'
request = require 'request'

app = http.createServer ( req, res ) ->

  console.log '1111'
  res.end '1231231'

app.listen './test.sock'
http = require 'http'

options = { socketPath : ‘./test.sock’ }

http.request options, () -> console.log ‘2222’

两个coffee文件,在同一个目录下面,先跑了第一个文件,然后再跑第二个文件,但是两边控制台均没有打印,请问下各位,这两段代码什么地方有问题?先谢过各位了哈。


5 回复

当然可以。你遇到的问题主要是由于 http.request 在尝试连接到通过 socketPath 提供的 Unix 套接字时,并没有正确地处理请求的结束或错误事件。这导致你的程序可能因为没有正确的回调处理而卡住,或者请求实际上并没有成功发送。

为了更好地理解这个问题并提供解决方案,我们可以使用 Node.js 的内置 http 模块来重写这两个脚本,并确保我们正确地处理了所有的事件。以下是修改后的代码:

服务端代码

const http = require('http');

const app = http.createServer((req, res) => {
  console.log('1111');
  res.end('1231231');
});

app.listen('./test.sock', () => {
  console.log('Server is listening on socket path: ./test.sock');
});

客户端代码

const http = require('http');

const options = {
  method: 'GET',
  socketPath: './test.sock'
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`Problem with request: ${e.message}`);
});

req.end();

在这个例子中:

  • 我们确保了服务器监听在指定的套接字路径 (./test.sock)。
  • 在客户端代码中,我们明确指定了请求的方法(这里是 GET),并且添加了对响应数据的监听器以及错误处理。

确保在运行客户端代码之前,服务器已经启动并且正在监听指定的套接字路径。这样,当客户端尝试连接时,服务器应该能够接收请求并返回响应,同时客户端也能够正确处理这些响应。


顶上去,跪求各位大神指导。

作为服务端的第一个文件大致ok,问题作为客户端的第二个文件中的request没有end。node中几乎所有的 write stream都强制性要求调用end()方法。

改为

http.get options, () ->
  console.log '2222'

或者


req=http.request options, () ->
  console.log '2222'
req.end()

options未指明method

太感谢了,果然就是这个原因,options未指明method的时候貌似默认就是get,非常感谢。

在这段代码中,问题在于 http.request 方法并没有被正确地处理。当你使用 socketPath 时,你需要确保请求是正确的,并且服务器已经在该路径上启动并监听。

示例代码

服务器端代码(server.coffee)

http = require 'http'

app = http.createServer (req, res) ->
  console.log '1111'
  res.end '1231231'

app.listen './test.sock', () ->
  console.log 'Server is listening on socketPath ./test.sock'

客户端代码(client.coffee)

http = require 'http'

options =
  method: 'GET'
  path: '/'
  hostname: 'localhost'
  port: null
  socketPath: './test.sock'

req = http.request options, (res) ->
  console.log '2222'
  res.on 'data', (chunk) ->
    console.log chunk.toString()

req.on 'error', (e) ->
  console.error "Problem with request: #{e.message}"

req.end()

解释

  1. 服务器端代码

    • 创建了一个 HTTP 服务器,监听名为 ./test.sock 的 Unix 套接字。
    • 当服务器成功启动后,会在控制台打印 Server is listening on socketPath ./test.sock
  2. 客户端代码

    • 使用 http.request 方法发起一个请求到 ./test.sock
    • 设置了请求方法为 GET,路径为 /
    • 在请求成功时,会在控制台打印 2222 并读取响应数据。

注意事项

  • 确保 server.coffee 先运行,等待服务器启动后再运行 client.coffee
  • 如果你在客户端收到错误信息,检查是否套接字路径正确以及服务器是否正常启动。
  • 你可以通过查看系统日志或调试工具来确认是否有任何异常发生。
回到顶部