C # TCP Server for easy chat

I am writing my first TCP server using Microsoft-provided Async examples.

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

I have everything that works on an example. I am expanding it as a simple chat program. But I am having problems after the steps of this program (possibly due to its asynchronous nature). When a message is received, it returns to the client and closes the socket. I do not see where he is returning to open the socket again.

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, isn’t it normal to open the socket?

+6
source share
1 answer

When a message is received, it returns to the client and closes the socket. I do not see where he is returning to open the socket again.

This is because it is not. The connection is in progress, the server receives, sends a response, and runs with this connection. He just keeps waiting for new connections in the listening jack. You have time (true). You will expect new incoming connections in the accept call. You will receive a new socket for each new client.

Also, is it okay to leave the socket open

Yes, the listening jack remains open. It is open to continue accepting new connections with accept

The best way to write an echo server using async and wait can be found here: Using .Net 4.5 Async Function for Socket Programming

+2
source

All Articles