Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# TCP Server for simple chat

Tags:

c#

tcp

sockets

I'm writing my first TCP server using Microsoft's supplied Async examples.

https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx

I have everything working from the example. I am extending it as a simple chat program. But I am having trouble following the steps of this program (probably because of its async nature). When a message is received, it echoes back to the client and closes the socket. I do not see where it goes back to re-open the socket.

public static void StartListening() {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // The DNS name of the computer
        // running the listener is "host.contoso.com".
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp );

        // Bind the socket to the local endpoint and listen for incoming connections.
        try {
            listener.Bind(localEndPoint);
            listener.Listen(100);

            while (true) {
                // Set the event to nonsignaled state.
                allDone.Reset();

                // Start an asynchronous socket to listen for connections.
                Console.WriteLine("Waiting for a connection...");
                listener.BeginAccept( 
                    new AsyncCallback(AcceptCallback),
                    listener );

                // Wait until a connection is made before continuing.
                allDone.WaitOne();
            }

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }

private static void SendCallback(IAsyncResult ar) {
        try {
            // Retrieve the socket from the state object.
            Socket handler = (Socket) ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = handler.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to client.", bytesSent);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

Also, is it not normal to leave the socket open?

like image 528
user3822370 Avatar asked Aug 08 '15 15:08

user3822370


Video Answer


1 Answers

When a message is received, it echoes back to the client and closes the socket. I do not see where it goes back to re-open the socket.

That is because it doesn't. The communication is done, the server receives, sends a reply and is done with that connection. It just continues to wait for new connections on the listening socket. You have a while (true). You'll keep waiting for new incoming connections in the accept call. You'll get a new socket for each new client.

Also, is it not normal to leave the socket open

Yes, the listening socket remains open. It is kept open to keep on receiving new connections using accept

A better way to write a echo server using async and await can be found here : Using .Net 4.5 Async Feature for Socket Programming

like image 184
Philip Stuyck Avatar answered Oct 09 '22 22:10

Philip Stuyck