jojo cadiente

jojo cadiente

  • NA
  • 8
  • 21.8k

C# Auto Reconnect Client to Server

Sep 27 2013 7:08 AM

Hello Could anybody help me about this I'm trying to create client and server application reverse connection. When I tried to open the client and server I didn't encounter any problem vise versa. The scenario is I execute the client and the server but when I closed the server and re open again it doesn't accept any connection.

Here is the Code:

CLIENT CODE:

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

 }
}


SERVER CODE:

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

        }

      }

     }
    }



Answers (2)