Hi,
I wrote a client/server application, I used TcpServer an TcpClient objects to enable this communications.
Server side I had no problem. It seems that when the client perform a request, the server reply so quickly. But Client side there is a little slowdown at the TcpClient initialization.
How use a single TcpClient initialization for all requests?
Thank you!
What I have tried:
I wrote this method:
TcpClient TcpClient = null;
NetworkStream TcpClientStream = null;
public string SendRequest(string command, out string response)
{
TcpClient = new TcpClient(TcpAddress, TcpPort);
TcpClientStream = TcpClient.GetStream();
byte[] msg = Encoding.ASCII.GetBytes(command);
TcpClientStream.Write(msg, 0, msg.Length);
byte[] result = new byte[0];
msg = new byte[TcpClient.ReceiveBufferSize];
int i;
while ((i = TcpClientStream(Read(msg, 0, msg.Length)) > 0)
{
Array.Resize(ref result, result.Length + i);
Array.Copy(msg, 0, result, result.Length - i, i);
}
TcpClientStream.Close(); TcpClientStream = null;
TcpClient.Close(); TcpClient = null;
return Encoding.ASCII.getString(result);
}
Result: Every time the TcpClient is initialized (
[1]
) there is a slowdown of about a second.
I tried to leave the TcpClient open replacing that statement with:
if (TcpClient == null)
TcpClient = new TcpClient(TcpAddress, TcpPort);
and commenting the
[4]
statement, but the
[2]
throws an InvalidOperationException (socket not connected).
I tried to check if it was not connected just after
[1]
:
if (!TcpClient.Connected)
TcpClient.Connect(TcpAddress, TcpPort);
The TcpClient.Connected is false, but the Connect method throws a SocketException (socket already connected)
I tried also to leave the TcpClientStream open commenting
[3]
and replacing
[2]
with:
if (TcpClientStream == null)
TcpClientStream = TcpClient.GetStream();
and this seems to run better. The TcpClientStream.Write is executed normally and without any slowdown, but the server doesn't receive the message.