Harry
Harry

Reputation: 15

tcp Server in c# chat app

I'm making chat app in c#. So I need help to make tcp server work without stopping. when I send message on server it is receiving it but then stops and doesn't receive another message...

 try
    {            
            IPAddress ipAd = IPAddress.Parse("127.0.0.1");

            TcpListener myList = new TcpListener(ipAd, 8001);
            myList.Start();

            Console.WriteLine("The server is running at port 8001...");
            Console.WriteLine("The local End point is  :" +
                              myList.LocalEndpoint);
            Console.WriteLine("Waiting for a connection.....");

            Socket s = myList.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

            byte[] b = new byte[100];
            int k = s.Receive(b);
            Console.WriteLine("Recieved...");
            for (int i = 0; i < k; i++)
                Console.Write(Convert.ToChar(b[i]));

            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The message was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");
            Console.ReadLine();
            //  s.Close();
            //myList.Stop();
    }
    catch (Exception e)
    {
        Console.WriteLine("Error..... " + e.StackTrace);
    }

Upvotes: 0

Views: 303

Answers (1)

Matt Stuvysant
Matt Stuvysant

Reputation: 488

There is no loop that would keep the TcpListener alive. You open the port and the wait for the first socket (myList.AcceptSocket(); is a blocking operation). Then you process the socket and terminate.

If you use a console application, it should end once it receives the first socket. If it is an interactive application (WPF, WinForm, …), its main loop will be kept running, but if there is no mechanism re-run your code, there is nothing that would receive other socket(s).

Provided you want to create a chat server, consider creating a windows service with non-blocking loop in it.

Upvotes: 0

Related Questions