public static async Task <Result <string> > SendMsgAsync(Socket socket, object message) { // Encode a string message before sending it to the server var messageData = ClientData <MessageData> .SerializeToByteArray(message); // Send it away var sendResult = await socket.SendWithTimeoutAsync( messageData, 0, messageData.Length, 0, SendTypeEnum.SendTypeCycle, CliServDefaults.SendTimeoutMs ) .ConfigureAwait(false); // If Task did not complete successfully, report the error if (sendResult.Failure) { return(Result.Fail <string>("There was an error sending data to the server")); } // Sent return(Result.Ok("Message sent.")); }
public void SendLoop(object arg) { Client client = arg as Client; if ((client != null) && (client.ClientSocket != null)) { while (!looper.LoopDone) { try { var eventData = GetDataAsync.GetMessageDataAsync(client.DataGetter, client.ClientHandle); if (eventData != null) { //if ((eventData.Result != null) && (eventData.Result.id > 0) && (eventData.Result.message != null)) if (eventData.Result != null) { byte[] buffer = ClientData <MessageData> .SerializeToByteArray <MessageData>(eventData.Result); var res = TcpLibExtensions.SendBufferAsync(client.ClientSocket, buffer, 0, buffer.Length, SocketFlags.None, client.CancelSource.Token); if (res.IsFaulted || (res.Result == null) || res.Result.Failure) { // Just close the socket. Look into trying to reconnect Console.WriteLine("Send Fault. Closing socket {0} to client.", client.ClientSocket.Handle); //ClientStore.RemoveClient((long)client.ClientSocket.Handle); } else if (eventData.Result.exitCmd) { Console.WriteLine("Exit Command Received"); ClientStore.RemoveClient((long)client.ClientSocket.Handle); client.Stop(); } else { // Data sent. Clear out buffer System.Diagnostics.Debug.WriteLine("Client {0} Sent Data.", client.ClientSocket.Handle); client.ClearData(); } } else { Console.WriteLine("Client: {0} -- NULL Message Result", client.ClientHandle); } } } catch (TaskCanceledException tc) { looper.LoopDone = true; System.Diagnostics.Debug.WriteLine("Send Task Cancelled: " + tc.Message); } catch (Exception e) { Console.WriteLine("Send Exception: " + e.Message); } } Console.WriteLine("Send Loop Exiting..."); } }