请教:使用Node.js的Net模块,如何指定Socket 客户端的本地端口,不是Socket服务端的监听端口
发布于 11 年前 作者 tanzt 7738 次浏览 最后一次编辑是 8 年前

各位, 用Node.js的Net模块,如何指定Socket 客户端的本地端口,不是Socket服务端的监听端口

同样的问题,请见 http://stackoverflow.com/questions/4023687/how-can-i-know-what-local-port-is-used-by-stream?s=82151331-7e71-4589-a55e-6f9ff0061abf#new-answer

How can I know, what local port is used by Stream?

Is it possible to specify explicitly local port that should be used by net.Stream, or to find out what local port is used for connection?

According to the documentation, local port cannot be specified:

Local port specified explicitly is required by Scala Remote Actors communication protocol - that’s what I need it for.

I want to open a client socket (not a server socket, which reacts to outgoing connections). Every client socket is bound to a local port, which is used to receive response from the server socket. I’m trying to figure out in runtime, which port is used. With netstat -tlnp it’s possible to figure out, which port is used by the client socket (by process ID), but I want to have something less cumbersome

According to the node.js documentation (http://nodejs.org/api.html) there is no method or variable exposed that provides the information you are looking for. I would suggest either submitting a patch (http://nodejs.org/#contributing) or making a request through a mailing list (http://groups.google.com/group/nodejs).

5 回复

算我孤陋寡闻了,就算是c也没有这个功能吧

你想要的是Bind这样的API吧,首先绑定一个本地端口,然后再建立连接。

这样的API我也没在node中找到,相关的只有一个localAddress选项。

参考:

http://nodejs.org/api/net.html#net_net_createconnection_options_connectionlistener

回复 @liuyanghejerry , Node的官方确实没有满足这种要求的的API,目前也没有看到有合适的直接解决方案;

@dengqiao C++和Java环境下,Socket的构造函数是有该功能的API的:目前考虑的解决方案:

  1. 尝试修改Node下的Net模块源代码 ;
  2. 由C ++ 和java建立绑定好的连接,由NOde调用 间接实现;

可以考虑在邮件列表向官方建议增加这样的API。特定场景下还是很实用的,更何况本身就是socket的API。

tcp :socket.localport 查看

udp: bind

回到顶部