I am writing tcp proxy server and i have trouble. After i caught request from client, i use such code:
var remoteStream = myRerouting.GetStream();
using (var clientStream = myClient.GetStream())
{
remoteStream.Write(httpRequest, 0, httpRequest.Length);
ReadSend(myRerouting.Client, clientStream);
}
ReadSend method code:
internal static void ReadSend(Socket mySocket, NetworkStream stream)
{
byte[] b = new byte[mySocket.ReceiveBufferSize];
int len = 0;
while (mySocket.Poll(1000000, SelectMode.SelectRead) && (len = mySocket.Receive(b, mySocket.ReceiveBufferSize, SocketFlags.None)) > 0)
{
stream.Write(b, 0, len);
}
}
And all is fine.
But when i want to process response(make some optimizations) and only then send response to client, something is going wrong and client don't receive an answer(i see something like "you tried to access the address which is currently unavailable"), though if i debug the code, i.e. move step by step, all is fine as earlier, buffer is filled properly and response is sent to client properly. Here is modified code:
var remoteStream = myRerouting.GetStream();
using (var clientStream = myClient.GetStream())
{
remoteStream.Write(httpRequest, 0, httpRequest.Length);
var buffer = ReadToEnd(myRerouting.Client);
clientStream.Write(buffer, 0, buffer.Length);
}
ReadToEnd method code:
private static byte[] ReadToEnd(Socket mySocket)
{
byte[] b = new byte[mySocket.ReceiveBufferSize];
int len = 0;
using (MemoryStream m = new MemoryStream())
{
while (mySocket.Poll(1000000, SelectMode.SelectRead) &&
(len = mySocket.Receive(b, mySocket.ReceiveBufferSize, SocketFlags.None)) > 0)
{
m.Write(b, 0, len);
}
return m.ToArray();
}
}
This is the only change. I don't understand why this is happening.