0

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

这是代码:

客户代码:

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();
            }

        }

      }

     }
    }
4

1 回答 1

0

而不是使用局部变量isConnected,您应该检查Connecting.Connected. 在您的情况下,您连接一次并设置isConnectedtrue. 现在你的while循环条件结束了false,你永远不会尝试重新连接你的客户端。

编辑:

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

    Thread.Sleep(millisecs);
}

请记住,您不应在 GUI 线程中运行此循环,因为它具有各种阻塞的可能性。如果您想与服务器交互,也只能尝试连接。但是现在这段代码应该适合你。

于 2013-09-27T09:12:04.210 回答