代码之家  ›  专栏  ›  技术社区  ›  user2528270

C#控制台自动将服务器重新连接到客户端

  •  0
  • user2528270  · 技术社区  · 11 年前

    您好,有人能帮我吗?我正在尝试创建客户端和服务器应用程序反向连接。当我试图打开客户端和服务器时,我没有遇到任何问题,反之亦然。场景是我执行客户端和服务器,但当我关闭服务器并再次打开时,它不接受任何连接,两个连接都丢失了。

    这是代码:

    客户端代码:

    namespace client1
    {
      class Program
       {
        public static bool isConnected { get; set; }
        public static NetworkStream Writer { get; set; }
        public static NetworkStream Reciever { get; set; }
    
        static void Main(string[] args)
        {
            Connect_To_Server();
        }
    
        public static void Connect_To_Server()
        {
            TcpClient Connecting = new TcpClient();
            string IP = "178.121.1.2";
            while (isConnected == false)
            {
                try
                {
                    Connecting.Connect(IP, 2000);
                    isConnected = true;
    
                    Writer = Connecting.GetStream();
                    Reciever = Connecting.GetStream();
                    Console.WriteLine("Connected: " + IP);
                }
                catch
                {
                    Console.WriteLine("Error Connection... .");
                    Console.Clear();
                }
            }
            Console.ReadKey();
        }
    
     }
    }
    

    服务器代码:

     namespace server1
     {
      class Program
       {
    
        public static bool isConnected { get; set; }
        public static NetworkStream Writer { get; set; }
    
        static void Main(string[] args)
        {
            Listen_To_Client();
        }
    
        public static void Listen_To_Client()
        {
            TcpListener Listen = new TcpListener(2000);
    
            while (true)
            {
                Listen.Start();
    
                if (Listen.Pending())
                {
    
                    TcpClient Connect = Listen.AcceptTcpClient();
                    isConnected = true;
                    Console.WriteLine("Connection Accepted");
                    Writer = Connect.GetStream();
                    Console.ReadKey();
                }
    
            }
    
          }
    
         }
        }
    
    1 回复  |  直到 11 年前
        1
  •  0
  •   Lukas Maurer    11 年前

    而不是使用局部变量 isConnected 你应该检查一下 Connecting.Connected . 在您的情况下,连接一次并设置 已连接 true 。现在你的 while 循环条件最终为 false 而且你永远不会试图重新连接你的客户。

    编辑:

    while (true)
    {
        try
        {
            TcpClient client = new TcpClient(ip, port);
            if (client.Connected)
            {
                // do something
                client.close();
            }
        }
        catch (SocketException) { }
    
        Thread.Sleep(millisecs);
    }
    

    请记住,您不应该在GUI线程中运行这个循环,因为它有各种阻塞的可能性。此外,只有当您想与服务器交互时,才尝试连接。但就目前而言,这段代码应该对您有效。