简体   繁体   English

TCP套接字到多个IP /端口

[英]TCP socket to multiple IP/port

I'm trying to write an application that connects to multiple IPs/ports and the problem I'm having is that the number of IPs is unknown to me, so one department can use it connect to 2 ips and other department may connect to 8, so it has to be configurable during runtime, I'm thinking of using threads or fork inside loop but not sure which one is better for the job, hope some one can guide me here, I'm using C under Linux. 我正在尝试编写一个连接到多个IP /端口的应用程序,而我遇到的问题是IP数量对我来说是未知的,因此一个部门可以使用它连接2个ips,而另一个部门可能连接到8个,因此它必须在运行时期间可配置,我在考虑使用线程或内部派生循环,但不确定哪一个更适合工作,希望有人可以在这里指导我,我在Linux下使用C。

For example one can run it like this a.out ip1 port1 ip2 port2 ip3 port3 and the other can run it like this a.out a.out ip1 port1 例如,一个可以像这样运行它a.out ip1 port1 ip2 port2 ip3 port3,另一个可以像这样运行它a.out a.out ip1 port1

Thanks 谢谢

I see four design choices here, each with advantages and disadvantages. 我在这里看到四个设计选择,每个选择都有优点和缺点。 Your choice will largely depend on what exactly your application does. 您的选择将在很大程度上取决于您的应用程序的确切功能。

  1. 1 process / socket (fork): This has the advantage that a fatal error in one process (eg, SEGFAULT) will not affect other processes. 1个进程/套接字(分支):这具有一个进程(例如SEGFAULT)中的致命错误不会影响其他进程的优点。 Disadvantages include the fact that the approach is more resource hungry and that processes are more difficult to coordinate (eg, if you want to do dynamic load balancing). 缺点包括以下事实:该方法更耗费资源,并且流程更难协调(例如,如果要进行动态负载平衡)。

  2. 1 thread / socket (pthreads): This has the advantage that it is pretty light and threads are easy to coordinate, since they share a common memory space. 1个线程/套接字(pthreads):优点是轻巧,线程易于协调,因为它们共享一个公共的内存空间。 Disadvantages include the fact that an error in one thread may take your whole application down. 缺点包括一个线程中的错误可能会使整个应用程序崩溃。

  3. Finite-State Machine: You could use a single thread in a single process, that does a huge poll on all your sockets, then takes the right (non-blocking) action, ie, read , write or close . 有限状态机:您可以在单个进程中使用单个线程,对所有套接字进行大量poll ,然后执行正确的(非阻塞)操作,即readwriteclose I heard this is very fast on a single processor, however, it does not take advantage of multi-core architecture and is somewhat more difficult to program. 我听说这在单个处理器上非常快,但是它没有利用多核体系结构,因此编程起来有些困难。

  4. Hybrid: pick any of the three above and combine them. 混合:选择以上三个中的任意一个并将其组合。 See for example the Apache server . 参见例如Apache服务器

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

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