multiport listening socket linux

一曲冷凌霜 提交于 2021-02-07 08:57:16

问题


I am writing a multithreaded server application, in C (linux), that must listen to 2 different port numbers, say listen to port no 3000 and 4000, for different clients connecting to it to serve different functionality (actual function is executed by a worker thread, main thread runs indefinitely and spawns of new workers upon new connections). I am not sure if select would work here as we can have multiple socket connections but all associated with same port number. I tried sequentially binding to sock_1 and sock_2. When I run client_1, everything works as expected. But, when I run client_2, I get an error on connect() from client side. If select() can be used here, please let me know how to do it. Any help much appreciated ! Thanks !

(P.S sock_1 refers to port no 3000 and sock_2 refers to port no 4000, client_1 refers to client thats seeking service from port 3000 and client_2 refers to client seeking service from same server from port no 4000)


回答1:


You have totally misunderstood socket and port, these two are different things. A port can have multiple sockets. but you can bind your listing socket(passive socket) to only a single port. Before going any further read this

If you want that your application listen on two different ports, have you bind two different sockets with it.

For a Quick reference a select in single process can only have upto 1024 socket descriptors. So if you are using a single process model then a select can only handle 1024 connections. Also read C10k problem see what suits your need.




回答2:


Using select() is great if your application has to accept data from more than one socket at a time since it will block until any one of a number of sockets is ready with data. One other advantage to select() is that you can set a time-out value after which control will be returned to you whether any of the sockets have data for you or not.
Following Links are useful to you:
http://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-2.html

Question-20
http://www.scribd.com/doc/7296598/Unix-Network-Programming-Volume-I-The-Sockets-Networking-API-3rd-Edition

Chapter-6: What I understood your application 'not required select()' Have a look on code at following link: http://kturley.com/simple-multi-threaded-web-server-written-in-c-using-pthreads/

Have call two different bind() for different ports in your code? As pointed by @Rahul Gautam in his answer.



来源:https://stackoverflow.com/questions/12740609/multiport-listening-socket-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!