tcpclient连接速度减慢

tcpclient连接速度减慢

本文介绍了tcpclient连接速度减慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我写了一个客户端/服务器应用程序,我使用TcpServer和TcpClient对象来启用此通信。



服务器端我没问题。似乎当客户端执行请求时,服务器回复得如此之快。但客户端在TcpClient初始化时有一点减速。



如何对所有请求使用单个TcpClient初始化?



谢谢!



我尝试过:



我写了这个方法:

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);      // [1]
   TcpClientStream = TcpClient.GetStream();             // [2]
   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;     // [3]
   TcpClient.Close(); TcpClient = null;                 // [4]
   return Encoding.ASCII.getString(result);
}





结果:每次初始化TcpClient时( [1] )减速约一秒钟。

我试图离开他用TcpClient打开替换该语句:



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);



并评论 [4] 语句,但 [2] 会抛出InvalidOperationException(套接字未连接)。

我试图在 [1] 之后检查它是否没有连接:


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);



TcpClient.Connected为false,但Connect方法抛出SocketException(套接字已连接)

我还试图让TcpClientStream打开评论 [3] 并替换 [2] with:


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();



这似乎运行得更好。 TcpClientStream.Write正常执行而没有任何减速,但是服务器没有收到消息。


and this seems to run better. The TcpClientStream.Write is executed normally and without any slowdown, but the server doesn't receive the message.

推荐答案



这篇关于tcpclient连接速度减慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:37