public async Task Send(T message) { if (message.Equals(default(T))) { throw new ArgumentNullException(nameof(message)); } bool alive = Socket.Ping(); if (!alive) { throw new TransferException($"The Socket to {EndPoint} is not responding!"); } try { // build byte[] out of message (serialize with ZeroFormatter) var bytes = ZeroFormatterSerializer.Serialize(message); var segment = new ArraySegment <byte>(bytes); int size = bytes.Length; await LeadingByteProcessor.SendLeading(Socket, size) .ConfigureAwait(false); // Send receiver the byte count //TODO: Decide whether to catch errors in buffer-loop and continue once fixed or cancel whole send? int written = 0; while (written < size) { int send = size - written; // current buffer size if (send > SendBufferSize) { send = SendBufferSize; // max size } var slice = segment.SliceEx(written, send); // buffered portion of array written = await Socket.SendAsync(slice, SocketFlags.None).ConfigureAwait(false); } if (written < 1) { throw new TransferException($"{written} bytes were sent! " + "Null bytes could mean a connection shutdown."); } } catch (SocketException) { ConnectionLost?.Invoke(EndPoint); // On any error - cancel whole buffered writing if (AutoReconnect) { await Reconnect().ConfigureAwait(false); // Try reconnecting and re-send everything once reconnected } else { throw; // Throw if we're not trying to reconnect } } }
public async Task Send(T message, IPEndPoint to) { if (message.Equals(default(T))) { throw new ArgumentNullException(nameof(message)); } // Build a byte array of the serialized data byte[] bytes = ZeroFormatterSerializer.Serialize(message); ArraySegment <byte> segment = new ArraySegment <byte>(bytes); // Find socket var socket = Sockets.FirstOrDefault(c => c.Key.Equals(to)).Value; if (socket == null) { throw new NetworkInterfaceException($"The IP Address {to} could not be found!"); } int size = bytes.Length; await LeadingByteProcessor.SendLeading(socket, size).ConfigureAwait(false); // send leading size //TODO: Do something when sending interrupts? Wait for client to come back? // Write buffered int written = 0; while (written < size) { int send = size - written; // current buffer size if (send > SendBufferSize) { send = SendBufferSize; // max size } ArraySegment <byte> slice = segment.SliceEx(written, send); // buffered portion of array written = await socket.SendAsync(slice, SocketFlags.None).ConfigureAwait(false); } if (written < 1) { throw new TransferException($"{written} bytes were sent! " + "Null bytes could mean a connection shutdown."); } }