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. 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值