TCPClient Performance Severly Lags Behind VB6 Winsock

S

Swiftusw

I'm writing a connector for a client to replace an old VB6 system. The
connector works, but is several times slower than the older VB6
connector. I have isolated the problem to be in the connection to the
server. All we are doing is sending a input stream to the server and
receiving an output stream in response. The code is below. Can anybody
see why this would run so much slower than VB6 using the Winsock
ActiveX control?

TIA,

Matt

public string SendMessage(string server, int port, string
requestMessage)
{
TcpClient client = new TcpClient();

client.SendBufferSize = 1024;
client.ReceiveBufferSize = 1024;

StringBuilder responseData = new StringBuilder();

byte[] data = Encoding.ASCII.GetBytes(requestMessage);

client.Connect(server, port);

NetworkStream stream = client.GetStream();

stream.Write(data, 0, data.Length);

data = new byte[client.ReceiveBufferSize];
int bytes = 0;

while(true)
{
bytes = stream.Read(data, 0, data.Length);
if(bytes>0){
responseData.Append(Encoding.ASCII.GetString(data, 0, bytes));
}
else{
break;
}
}

stream.Close();
client.Close();

return responseData.ToString();
}
 
J

Jon Skeet [C# MVP]

Swiftusw said:
I'm writing a connector for a client to replace an old VB6 system. The
connector works, but is several times slower than the older VB6
connector. I have isolated the problem to be in the connection to the
server. All we are doing is sending a input stream to the server and
receiving an output stream in response. The code is below. Can anybody
see why this would run so much slower than VB6 using the Winsock
ActiveX control?

Have you tried using a longer receive buffer? It might be worth using a
network analyser to find out what socket options the Winsock control is
using.

Are you seeing much load on either system?
 
S

Swiftusw

I figured it out -- The original while{} loop over-ran while trying to
capture every byte that came through. By having the thread sleep on
each iteration of the while loop, it allowed the buffer to fill up.
Basically, all I did was change the while loop to this:

do
{
data = new byte[client.ReceiveBufferSize];
bytes = stream.Read(data, 0, data.Length);
responseData.Append(Encoding.ASCII.GetString(data, 0, bytes));
System.Threading.Thread.Sleep(500);
}
while(stream.DataAvailable);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top