Page 136 - CSharp/C#
P. 136
{
try
{
MessageBox.Show($"Listening started port:{Port} protocol type:
{ProtocolType.Tcp}");
ListenerSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
ListenerSocket.Listen(10);
ListenerSocket.BeginAccept(AcceptCallback, ListenerSocket);
}
catch(Exception ex)
{
throw new Exception("listening error" + ex);
}
}
So when a client connects we can accept them by this method:
Three methods wee use here are:
1. ListenerSocket.EndAccept()
We started the callback with Listener.BeginAccept() end now we have to end that call back.
The EndAccept() method accepts an IAsyncResult parameter, this will store the state of the
asynchronous method, From this state we can extract the socket where the incoming
connection was coming from.
2. ClientController.AddClient()
With the socket we got from EndAccept() we create an Client with an own made method
(code ClientController below server example).
3. ListenerSocket.BeginAccept()
We need to start listening again when the socket is done with handling the new connection.
Pass in the method who will catch this callback. And also pass int the Listener socket so we
can reuse this socket for upcoming connections.
public void AcceptCallback(IAsyncResult ar)
{
try
{
Console.WriteLine($"Accept CallBack port:{Port} protocol type:
{ProtocolType.Tcp}");
Socket acceptedSocket = ListenerSocket.EndAccept(ar);
ClientController.AddClient(acceptedSocket);
ListenerSocket.BeginAccept(AcceptCallback, ListenerSocket);
}
catch (Exception ex)
{
throw new Exception("Base Accept error"+ ex);
}
}
Now we have an Listening Socket but how do we receive data send by the client that is what the
https://riptutorial.com/ 82

