/// <summary> /// Send the data in a byte array to the server. /// Expects a delegate to be assigned to ProcessBytesMethod which will handle the data. /// </summary> /// <param name="reloadedSocket">The individual reloadedSocket object connected to either a host or client.</param> /// <param name="message">The message that is to be sent to the server.</param> /// <param name="awaitResponse">Set true to wait for a response from the server, else false.</param> public static Message.MessageStruct SendData(this ReloadedSocket reloadedSocket, Message.MessageStruct message, bool awaitResponse) { try { // Return empty message if socket not connected. if (!reloadedSocket.Socket.Connected) { return(null); } // Convert the message struct into bytes to send. byte[] data = message.BuildMessage(); // Get the amount of bytes sent. int bytesSent = 0; // Ensure we send all bytes. while (bytesSent < data.Length) { // Offset: Bytes Sent // Length to Send: Length to send - Already Sent int bytesSuccessfullySent = reloadedSocket.Socket.Send(data, bytesSent, data.Length - bytesSent, SocketFlags.None); // Send serialized Message! bytesSent += bytesSuccessfullySent; // If the reloadedSocket is not connected, return empty message struct. if (bytesSuccessfullySent == 0) { if (!IsSocketConnected(reloadedSocket)) { return(null); } } } // If we want a response from the client, receive it, copy to a buffer array and send it back to the method delegate linked to the method we want to process the outcome with. if (awaitResponse) { return(ReceiveData(reloadedSocket)); } return(null); } catch // Probably lost connection. { reloadedSocket.CloseIfDisconnected(); return(null); } }
/// <summary> /// Send the data in a byte array to the server. /// Expects a delegate to be assigned to ProcessBytesMethod which will handle the data. /// </summary> /// <param name="reloadedSocket">The individual reloadedSocket object connected to either a host or client.</param> /// <param name="message">The message that is to be sent to the server.</param> public static void SendDataAsync(this ReloadedSocket reloadedSocket, Message.MessageStruct message) { try { // Return empty message if socket not connected. if (!reloadedSocket.Socket.Connected) { return; } // Convert the message struct into bytes to send. reloadedSocket.DataToSend = message.BuildMessage(); // Set sent bytes to 0. reloadedSocket.AsyncBytesToSend = reloadedSocket.DataToSend.Length; reloadedSocket.AsyncSentBytes = 0; // Begin sending the message. reloadedSocket.Socket.BeginSend(reloadedSocket.DataToSend, 0, reloadedSocket.DataToSend.Length, SocketFlags.None, SendAsyncCallback, reloadedSocket); } catch { reloadedSocket.CloseIfDisconnected(); } }