灰太狼的博客

除了照顾红太狼,小灰灰,抓喜洋洋外,我这个灰太狼还要写程序。

How to resolve Time_Wait issue when you use TcpListener and TcpClient

Issue description:

If you use TcpListener and TcpClient to communicate, it will produce more Time_Wait status in socket pipe. I get the TcpListener and TcpClient sample from MSDN

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx

The issue can be re-produced.  I search so many solutions from internet, but no correct answer. I cost two days to research it and finally I resolve it.

Look at following sample code, the part of code references by MSDN.

TcpClient:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 port = 4066;
            for (int i = 0; i < 10; i++)
            {
                using (TcpClient client = new TcpClient("127.0.0.1", port))
                {
                    string message = "message";
                    // Translate the passed message into ASCII and store it as a Byte array.
                    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

                    using (NetworkStream stream = client.GetStream())
                    {
                        // Send the message to the connected TcpServer. 
                        stream.Write(data, 0, data.Length);
                        Console.WriteLine(@"Send data to server at {0}", DateTime.Now.ToString("HH:mm:ss"));
                        stream.Close();
                    }
                    client.Close();
                    Thread.Sleep(1000);
                }
            }
            Console.ReadLine();
        }
    }
}

TcpListener:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace ConsoleServer
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener server = null;
            try
            {
                Int32 port = 4066;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data = null;

                // Enter the listening loop.
                while (true)
                {
                    //Console.WriteLine("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    string ip = client.Client.RemoteEndPoint.ToString();
                    Console.WriteLine(string.Format("{0} Connected!",ip));

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;
                    
                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Console.WriteLine("Received: {0}", data);
                    }
                    
                    if(i ==0)// Client is disconnected.
                    {
                        //stream.WriteByte(0);
                        Console.WriteLine("{0} disconnect", ip);
                    }

                    // Shutdown and end connection
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                server.Stop();
            }

            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
    }
}

Running the above code, you will get following output screen:

Now please use netstat or other tool to check the socket pipe. I use netstat, the screen like following:



So look, there are so many Time_Wait status. The Time_Wait means the socket is waiting for remote data. Why? If you use the MSDN sample, the result is the same.


Reason:

As the Time_Wait meaning, we know that the connected socket is waiting for remote data. We know the tcp need to hander three times, so if you close socket directly, the remote connection will entry a Time_Wait status or produce exception.


Solution:

Look at above "TcpListener code", pay attention to the deleted code row:

if(i ==0)// Client is disconnected.
                    {
                        //stream.WriteByte(0);
                        Console.WriteLine("{0} disconnect", ip);
                    }

i==0 means the remote data has finished or remote has dis-connected. At this time, if you close local socket, then the client socket will keep a Time_Wait Status for a while. So you must send any of data to client, and stop the client Time_Wait.

The solution is so easy, recovery the "stream.WriteByte(0)" code:

if(i ==0)// Client is disconnected.
                    {
                        stream.WriteByte(0);
                        Console.WriteLine("{0} disconnect", ip);
                    }

Then you run the code again, and check the socket status, the Time_Wait is dismiss.



This article is from http://blog.csdn.net/tjvictor By Victor Guo. If you want to forward it , please remark the article original Url. 

阅读更多
个人分类: C#相关知识
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭