// callbacks private void SendCallback(IAsyncResult ar) { try { StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; int bytesSent = handler.EndSend(ar); string socketName = GetSocketName(handler); WriteLog(LogFormats.BytesWereSentSuccessfuly(bytesSent, socketName)); if (Encoding.UTF8.GetString(state.buffer).IndexOf(endMessage) != -1) { WriteLog(LogFormats.ClosingSocket(socketName)); handler.Close(); return; } state.buffer = new byte[100]; state.workSocket = handler; handler.BeginReceive(state.buffer, 0, state.BufferSize, SocketFlags.Partial, new AsyncCallback(ReceiveCallback), state); WriteLog(LogFormats.WaitingToReceiveResultFromWorker(socketName)); } catch (Exception e) { WriteLog(LogFormats.ExceptionWasThrownString(e)); } }
// Starting to listen to the connections private void StartListening() { IPHostEntry ipHostInfo = Dns.GetHostEntry(host); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, socketPort); listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { WriteLog(LogFormats.TryingToBindSocketToLocalEndPoint(localEndPoint)); listener.Bind(localEndPoint); WriteLog(LogFormats.bindingWasSuccessfulString); WriteLog(LogFormats.tryingToListenString); listener.Listen(numberOfPossibleListeners); WriteLog(LogFormats.listeningWasStartedString); Thread thrd = new Thread(() => { for (int i = 0; i < numberToAccept; i++) { listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); } }); thrd.Start(); } catch (Exception e) { WriteLog(LogFormats.ExceptionWasThrownString(e)); } }