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

时间:2013-09-27 08:28:25

标签: c# c#-4.0 tcp tcpclient tcplistener

你好任何人可以帮助我这个我正在尝试创建客户端和服务器应用程序反向连接。当我试图打开客户端和服务器时,我没有遇到任何问题反之亦然。方案是我执行客户端和服务器,但当我关闭服务器并再次打开时,它不接受任何连接两个连接丢失。

以下是代码:

客户代码:

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 个答案:

答案 0 :(得分:0)

您应该检查isConnected,而不是使用本地变量Connecting.Connected。 在您的情况下,您连接一次并将isConnected设置为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线程中运行此循环,因为它具有各种阻塞潜力。如果要与服务器交互,也只尝试连接。但是现在这段代码应该适合你。

相关问题