/// <summary> /// Shutdown the specificed socket. /// </summary> /// <param name="socket">The socket that needs to be /// shutdown.</param> public static void ShutdownSocket(Socket socket) { if (socket.Connected) { DebugUtilities.Log("Closing socket on port " + socket.LocalEndPoint); socket.Shutdown(SocketShutdown.Both); socket.Disconnect(false); } }
/// <summary> /// Callback of the asynchronous socket while /// message is sent to the client. /// </summary> /// <param name="ar">Result of the async task.</param> 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); DebugUtilities.Log( TAG + "Send " + bytesSent + " bytes to client." ); messageSender.OnSendComplete(); } catch (Exception ex) { messageSender.OnSendFail(ex.Message); } }
/// <summary> /// Places the socket in a listening state and begins /// to accept connections. /// </summary> /// <param name="socket"></param> /// <param name="receiver">An instance of /// NetworkUtilities.IMessageReceiver that handles the /// callbacks for receiving data from remote socket client.</param> /// <param name="sender">And instance of /// NetworkUtilities.IMessageSender that handles the /// callbacks for sending data to remote socket client.</param> /// <param name="backlog">The maximum length of the /// pending connections queue. Default value is 10.</param> public static void StartListening(Socket socket, IMessageReceiver receiver, IMessageSender sender, int backlog = 10) { messageReceiver = receiver; messageSender = sender; // Listen for incoming connections socket.Listen(backlog); // Start an asynchronous socket to listen for // connections. socket.BeginAccept(new AsyncCallback(AcceptCallback), socket); // For logging purpose. string localAddr = socket.LocalEndPoint.ToString(); DebugUtilities.Log( TAG + "Server is now listening on " + localAddr ); }