read and write to same socket (TCP) using select

前端 未结 4 445
悲&欢浪女
悲&欢浪女 2020-12-16 18:00

We\'re writing a client and a server to do (what I thought was) pretty simple network communications. Mulitple clients connect to the server which then is supposed to send

相关标签:
4条回答
  • 2020-12-16 18:06

    2 threads should be able to work with the same socket at a time, so your main thread should be able to write to a client while the other one sleeps in select waiting for incoming data. This of course assumes that both threads have access to the client list.

    0 讨论(0)
  • 2020-12-16 18:11

    Everything looks fine, except the line where you do if (FD_SET(sockfd, &master_list)). I have a very similar code structure and I used FD_ISSET. You're supposed to test if the list is set, not to set it again. Other than that, I see nothing else.

    Edit. Also, I have the following for the timeout:

    timeval listening_timeout;
    listening_timeout.tv_sec = timeout_in_seconds;
    listening_timeout.tv_usec = 0;
    

    perhaps there's an issue if you set it to 0 (as you seem to be doing?)

    Edit2. I remembered I ran into a strange problem when I wasn't clearing the read set after the select exited and before I entered it again. I had to do something like:

    FD_ZERO(&sockfd);
    FD_SET(sockfd, &rd);
    

    before I was entering select. I can't remember why though.

    0 讨论(0)
  • 2020-12-16 18:23

    I don't see anything wrong with your code, so it should work. If you can't get it working, one way to work around it would be to create a pipe to be used by your reading thread and the thread that prepares things for writing, and add the pipe's reading end to your select set. Then, when the other thread has prepared data to write, it just sends something on the pipe, your reading thread gets woken up from the select, and it can then do the writing. Depending on how often there is data to read or write, this could also be more efficient.

    0 讨论(0)
  • 2020-12-16 18:30

    I seem to recall a trick about creating and sharing a read/write filedescriptor between the network thread and the main thread that is added to the descriptors in the select call. This fd has one byte written to it by the main thread when it has something to send. The write wakes up network thread from the select call and the network thread is then grabs the data from a shared buffer and writes it to the network then go back to sleep in the select.

    Sorry if that's a bit vague and lacking of code ... and my memory may be incorrect.. so others may have to guide you further.

    0 讨论(0)
提交回复
热议问题