C# Socket TCP Send, messages getting “stuck”

前端 未结 5 833
感情败类
感情败类 2021-01-15 10:45

This is a bit of an odd one and apologies if I don\'t explain it very well.

I am using the following simple code to send messages that I have popped off a queue, usi

5条回答
  •  长情又很酷
    2021-01-15 11:26

    I am not sure if this is your problem and I am working off of a vague memory from yesteryear so please excuse the vagueness.

    I seem to remember that Socket.Select() would return indicating it has zero data to read if the stream has an error. You may want to try passing a copy of the stream list in to the error list parameter and see if you get any in error.

    Your code appears to be sending to the same socket regardless of what is in writelist. I would modify it to operate on the writelist even if you only have a single socket. Otherwise you'll be attempting to send to a socket even if it has not necessarily indicated it is ready for data yet (i.e. if the Socket.Select() is returning for some other reason, such as my hunch above). This may cause the write operation to block and may be the cause of the delay you are witnessing if you are operating with more than one socket.

    Finally, you can break out of your readyToWrite loop as soon as the flag is set. Better still you can recode this as:

    bool readyToWrite = writelist.Any();
    

    But I would still suggest you replace this with a foreach loop on writelist:

    foreach (Socket sock in writelist)
    {
        // do stuff
    }
    

提交回复
热议问题