C#Chat - 即使服务器不接受,客户端也在连接

时间:2017-12-24 00:04:55

标签: c# tcp tcpclient tcplistener

我在C#(控制台应用程序)中进行了简单的聊天,

这是我的服务器:

static readonly object _lock = new object();
    static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();

    static void Main(string[] args)
    {
        int count = 1;
        TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000);
        ServerSocket.Start();

        while (true)
        {
            TcpClient client = ServerSocket.AcceptTcpClient();
            lock (_lock) list_clients.Add(count, client);
            Console.WriteLine("Client connected");
            Thread t = new Thread(handle_clients);
            t.Start(count);
            count++;
        }
    }

    public static void handle_clients(object o)
    {
        int id = (int)o;
        TcpClient client;

        lock (_lock) client = list_clients[id];

        while (true)
        {
            NetworkStream stream = client.GetStream();
            byte[] buffer = new byte[1024];
            int byte_count = stream.Read(buffer, 0, buffer.Length);

            if (byte_count == 0)
            {
                break;
            }

            string data = Encoding.ASCII.GetString(buffer, 0, byte_count);
            Console.WriteLine(data);
        }

        lock (_lock) list_clients.Remove(id);
        client.Client.Shutdown(SocketShutdown.Both);
        client.Close();
    }

这是我的客户:

static void Main(string[] args)
    {
        IPEndPoint ipep = new IPEndPoint(Dns.GetHostAddresses("hostname.net").FirstOrDefault(), 5000);
        TcpClient client = new TcpClient();
        client.Connect(ipep);
        Console.WriteLine("Connected to the server");
        NetworkStream ns = client.GetStream();
        Thread thread = new Thread(o => ReceiveData((TcpClient)o));

        thread.Start(client);

        string s;
        while (!string.IsNullOrEmpty((s = Console.ReadLine())))
        {
            byte[] buffer = Encoding.ASCII.GetBytes(s);
            ns.Write(buffer, 0, buffer.Length);
        }

        client.Client.Shutdown(SocketShutdown.Send);
        thread.Join();
        ns.Close();
        client.Close();
        Console.WriteLine("Disconnected");            
        Console.ReadKey();
    }

问题是客户端连接到服务器,但服务器未找到客户端已连接,即使我关闭服务器,客户端仍保持连接状态。当我从localhost切换到no-ip主机以使聊天“公开”时,这个问题就开始发生了。

我在哪里做错了?

提前致谢。

0 个答案:

没有答案