This is the first real application I am trying to create with .Net Socket classes (Sockets, TCPClient, TCPListener) using C#. Unfortunately the MSDN documentation is not very good, and the examples they give are far too simplistic for my real world application. So I am hoping that some people here can give me some answers from their experiences. I believe I understand how the classes work in general, but there are many questions I can not seem to find answers to. What I need to create is a full duplex TCP connection between my server and a variety of different clients. Only 1 client will connect at a time, BUT I have absolutely no control over the client in any way. The only agreement between the two systems are the message formats (as there are different types of messages), and the byte sequences that delineate the start and end of these messages. The connection must remain open, and messages can be received at any time from the client, as well as be sent any time from the server in response to local system events. So my first question is can a single socket, or tcpclient, read and write data at the same time from different threads. My thinking at first was to use two separate threads; one that blocks on a Read method, while the other writes data as needed, but I am not sure if one instance can be shared safely between two threads, and if reading and writing at one time is even possible. My other thought was to use the beginread method with a call back and write data using the beginwrite method, being the callbacks will be on a separate threads, but again I am not sure this is possible. My final thought was to just poll the dataavailable method, and if data was available then read it with the read method, and in the same polling loop write any data that needs to be written. The problem here is that if the client disconnects the dataavailable method just returns false and I have no way of knowing the client closed the connection unless the server tries to write, which could be hours later. In the meantime the client is unable to send any messages. Also, I would prefer to not poll as I don't want to unnecessarily use up processor time, and I really do not want to use thread.sleep to mitigate the effects of polling. I would much rather wait on callbacks or blocks. I hope I am explaining this correctly and I think I am just missing something. Any help would be greatly appreciated.
Thanks in advance.