c#tcpListener侦听多个客户端的连接状态

时间:2015-07-06 08:47:37

标签: c#

我正在尝试将多个客户端连接到服务器并监控其连接...

我正在尝试在创建这些程序时更好地了解TcpListenerTcpClient

我从另一个stackoverflow回答中找到了我的服务器代码,因为我希望从多个客户端获得连接,我已经编辑了abit:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace socket_server
{
    class connect
    {
        public class State
        {
            public Socket workSocket = null;
            public const int bufferSize = 1024;
            public byte[] buffer = new byte[bufferSize];
            public StringBuilder sb = new StringBuilder();
        }

        public class Server
        {
            public static ManualResetEvent allDone = new ManualResetEvent(false);

            private static IPEndPoint findMe()
            {
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5505);
                return localEndPoint;
            }

            public static void start()
            {
                try
                {
                    TcpListener listener = new TcpListener(findMe());
                    TcpClient client;
                    listener.Start();

                    Console.WriteLine("Server IP: {0}\n", findMe());
                    Console.WriteLine("Waiting for Connection...");

                    while (true)
                    {
                        client = listener.AcceptTcpClient();
                        ThreadPool.QueueUserWorkItem(threadProc, client);
                    }

                    Console.ReadKey();
                } catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
            private static void threadProc(object obj)
            {
                try
                {
                    var client = (TcpClient)obj;
                } catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
    }
}

您可以将其称为connect.Server.start()

这是我目前的客户代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace socket_client
{
    class connect
    {
        public class State
        {
            public Socket workSocket = null;
            public const int bufferSize = 256;
            public byte[] buffer = new byte[bufferSize];
            public StringBuilder sb = new StringBuilder();
        }

        public class Client
        {
            private const int port = 5505;    
            private static String response = String.Empty;

            private static IPEndPoint findServer()
            {
                IPHostEntry ipHostInfo = Dns.Resolve("10.1.2.30");
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
                return remoteEP;
            }

            public static void start()
            {
                TcpClient client = new TcpClient();

                Console.WriteLine("Server IP: {0}", findServer().ToString());
                Console.WriteLine("Client IP: {0}\n", software.getIPAddress());

                connect(client);
                if (client.Connected)
                    Console.WriteLine("\nConnected to: {0}\n", findServer().ToString());
            }

            private static void connect(TcpClient client)
            {
                try
                {
                    client.Connect(findServer());
                } catch(Exception e)
                {
                    Console.WriteLine("Attempting to connect to: {0}", findServer().ToString());
                    connect(client);
                }

            }
        }
    }
}

您可以将其称为connect.Client.start();

我的类hardwaresoftware只是获取系统信息。

我想知道如何检查连接是否已被删除,并以客户端和服务器的Console.WriteLine进行响应。

修改 -

这是我工作用于检查客户端是否从服务器中删除的内容:

...
private static void threadProc(object obj)
{
    try
    {
        var client = (TcpClient)obj;

        Byte[] bytes = new Byte[256];
        string data = null;

        try { 
            NetworkStream stream = client.GetStream();

            int i;
            while((i = stream.Read(bytes,0,bytes.Length)) != 0)
            {
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine(">{0}: {1}", ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString(), data);
            }
        } catch(Exception e)
        {
            Console.WriteLine(">>{0} Lost Connection...", ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
        }
    } catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}
...

1 个答案:

答案 0 :(得分:0)

当您在流上阅读失败时,您将只能检测连接是否已关闭,因为没有可以通知您的事件。

您可以在连接处理类中引发自己的事件。

但由于某些原因,有可能TCP-Connection在没有挂起Read()的情况下丢失 - 调用失败。 因此,没有完美的方法,比如处理事件,当连接断开时,它始终会通知您。所以你必须实现一些保持活动机制。例如。每隔一段时间发送一次ping / pong并等待答案。如果在定义的时间内没有应答,您可以关闭连接。