I am trying to learn more about sockets and threading in c#. I have come across a lot of good resources online to help get me started. The program I made so far, is a simple
The most efficient way of handling this would be to issue a read with a callback, on each stream.
After issuing both reads, sit waiting forever on an object that you use to signal that the thread should stop its work (a ManualResetEvent is the traditional one to use - can be used to signal many threads at once).
When data is received, the OS will call your callback function(s), and you would do your processing in there and then (importantly) queue another read.
This means that your thread is forever idle, waiting on a signal object that tells it that it's time to go away (in a "wake up - time to die" kind of way), and is only ever doing work when the OS tells it that there is data to process.
To be REALLY friendly, you would also do the writes asynchronously, so that one connection cannot starve the other of processing time (in the current implementation, if one write blocks, the other stream never gets serviced).
Finally, to be super good, you would encapsulate this behaviour in an object that takes as a parameter the stream to use, and then simply instantiate two of them, instead of having two streams and doing everything twice in the main code.
After accepting the socket in the middle man I do the following:
private void WaitForData()
{
try
{
if (socketReadCallBack == null)
{
socketReadCallBack = new AsyncCallback(OnDataReceived);
}
ReceiveState rState = new ReceiveState();
rState.Client = mySocket;
mySocket.BeginReceive(rState.Buffer, 0, rState.Buffer.Length, SocketFlags.None,
new AsyncCallback(socketReadCallBack), rState);
}
catch (SocketException excpt)
{
// Process Exception
}
}
Receive State is:
public class ReceiveState
{
public byte[] Buffer = new byte[1024]; //buffer for network i/o
public int DataSize = 0; //data size to be received by the server
public bool DataSizeReceived = false; //whether prefix was received
public MemoryStream Data = new MemoryStream(); //place where data is stored
public Socket Client; //client socket
}
Once data is received my routine "OnDataReceived" processes it. I'm not experiencing any CPU problems with this.
Same code used for both the client and middleman.