简体   繁体   中英

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.

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

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. 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. 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 . 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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