简体   繁体   English

C#中TCP通信的服务器端口繁忙问题

[英]Server port busy issue with TCP Communication in C#

i have used TCP communication in C# for client server communication.我在 C# 中使用 TCP 通信进行客户端服务器通信。

Many of the clients are trying to connect to TCP server at a time.许多客户端一次尝试连接到 TCP 服务器。

i am facing server port busy issue.我正面临服务器端口繁忙的问题。 below is my server and client code.下面是我的服务器和客户端代码。

is there any way, i can solve the server port busy issue.有什么办法,我可以解决服务器端口繁忙的问题。

Server Code
     /// <summary>
        /// 
        /// </summary>
        public void initializeListener(int iPortNumber,int iActivationPortNumber)
        {
            try
            {
                // BLTablePrototype.TablePrototypeDetails();
                System.Net.IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                System.Net.IPAddress ipaddress = ipHostInfo.AddressList[0];

                serverSocket = new TcpListener(ipaddress, iPortNumber);

                try
                {
                    serverSocket.Stop();

                }
                catch { }

                serverSocket.Start();

                Common.BLConstants.isListnerStarted = true;



                //StartAccept();
                //WaitForClients();
            }
            catch (Exception ex)
            {

            }
        }


        public void ReceiveTCP()
        {  
            try
            {
                while (true)
                {
                    if (serverSocket.Pending())
                    {
                        TcpClient client = client = serverSocket.AcceptTcpClient();                        
                        if (client.Connected)
                        {
                            Thread thread = new Thread(WorkThread);
                            thread.Start(client);
                        }                      
                    }
                    else
                    {
                        Thread.Sleep(30000);
                    }
                }

            }
            catch (Exception ex)
            {

            }

        }


client Code

  client = new TcpClient();
                var result = client.BeginConnect(Wipro.EUA.Library.Cryptography.Decrypt(Common.BLConstants.strServerIPAddress), iPortnumber, null, null);
                result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2));

                if (client.Connected)
                {

                    byte[] SendingBuffer = Encoding.UTF8.GetBytes(XElement.ToString());
                    netstream = client.GetStream();

                    int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(SendingBuffer.Length) / Convert.ToDouble(BLConstants.iBufferSize)));
                    int TotalLength = (int)SendingBuffer.Length, CurrentPacketLength, FinalLength = 0, RemainingLength = TotalLength;
                    for (int k = 0; k < NoOfPackets; k++)
                    {
                        if (RemainingLength > BLConstants.iBufferSize)
                        {
                            if (k == 0)
                                CurrentPacketLength = k * BLConstants.iBufferSize;
                            else
                                CurrentPacketLength = k * BLConstants.iBufferSize;

                            FinalLength = CurrentPacketLength + BLConstants.iBufferSize;
                            RemainingLength = TotalLength - FinalLength;
                            netstream.Write(SendingBuffer, CurrentPacketLength, BLConstants.iBufferSize);
                        }
                        else
                        {
                            CurrentPacketLength = FinalLength;
                            netstream.Write(SendingBuffer, CurrentPacketLength, TotalLength - CurrentPacketLength);
                        }
                    }
                }

                client.EndConnect(result);
                isSuccess = true;

i have used TCP communication in C# for client server communication.我在 C# 中使用 TCP 通信进行客户端服务器通信。

Many of the clients are trying to connect to TCP server at a time.许多客户端一次尝试连接到 TCP 服务器。

i am facing server port busy issue.我正面临服务器端口繁忙的问题。 below is my server and client code.下面是我的服务器和客户端代码。

is there any way, i can solve the server port busy issue.有什么办法,我可以解决服务器端口繁忙的问题。

The issue as @MickyD commented, is the line: @MickyD 评论的问题是:

Thread.Sleep(30000);

You accept only one connection and then sleeps for 30 seconds.您只接受一个连接,然后休眠 30 秒。 Obviously, clients that will try to connect during those 30 seconds, will not get a reponse (timeout).显然,在这 30 秒内尝试连接的客户端将不会得到响应(超时)。

Actually, the solution is very simple.其实,解决办法很简单。
You don't need all that login with the Pending and Sleep您不需要使用PendingSleep所有登录
It's enough to use only AcceptTcpClient .仅使用AcceptTcpClient足够了。

AcceptTcpClient is a blocking method. AcceptTcpClient是一种阻塞方法。 It will block until a connection arrives.它将阻塞,直到连接到达。

The reason for using Pending is if you don't want to block, but you are blocking any way with the Thread.Sleep(30000)使用Pending的原因是如果你不想阻塞,但你正在以任何方式阻塞Thread.Sleep(30000)

All this is covered by the documentation :所有这些都包含在文档中

AcceptTcpClient is a blocking method that returns a TcpClient that you can use to send and receive data. AcceptTcpClient 是一种阻塞方法,它返回可用于发送和接收数据的 TcpClient。 Use the Pending method to determine if connection requests are available in the incoming connection queue if you want to avoid blocking.如果您想避免阻塞,请使用 Pending 方法来确定传入连接队列中是否有可用的连接请求。

Also, you don't need to check if the client is connected(You are getting a connected connection...) So, your loop can become simpler:此外,您不需要检查客户端是否已连接(您正在连接连接...)因此,您的循环可以变得更简单:

while (true)
{
    TcpClient client = client = serverSocket.AcceptTcpClient();                        
    Thread thread = new Thread(WorkThread);
    thread.Start(client);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM