public static PeerListenerEndPoint Deserialize(byte[] data) { PeerListenerEndPoint result = new PeerListenerEndPoint(); int offset = 0; result.ConnectionType = (Connections.ConnectionType)BitConverter.ToInt32(data, offset); offset += sizeof(int); if (result.ConnectionType == ConnectionType.TCP || result.ConnectionType == ConnectionType.UDP) { byte[] address = new byte[BitConverter.ToInt32(data, offset)]; offset += sizeof(int); Buffer.BlockCopy(data, offset, address, 0, address.Length); offset += address.Length; int port = BitConverter.ToInt32(data, offset); offset += sizeof(int); result.EndPoint = new IPEndPoint(new IPAddress(address), port); } #if NET35 || NET4 else if (result.ConnectionType == ConnectionType.Bluetooth) { byte[] address = new byte[8]; Buffer.BlockCopy(data, offset, address, 0, address.Length); offset += address.Length; byte[] service = new byte[16]; Buffer.BlockCopy(data, offset, service, 0, service.Length); offset += service.Length; result.EndPoint = new BluetoothEndPoint(new BluetoothAddress(address), new Guid(service)); } #endif else throw new Exception(); return result; }
/// <summary> /// Serializes the local listeners that are discoverable /// </summary> /// <returns></returns> private static byte[] SerializeLocalListenerList() { List<ConnectionListenerBase> allListeners = Connection.AllExistingLocalListeners(); using (MemoryStream ms = new MemoryStream()) { ms.Write(NetworkComms.NetworkIdentifier.Guid.ToByteArray(), 0, 16); int discoverableCount = 0; ms.Seek(sizeof(int) + 16, SeekOrigin.Begin); foreach (ConnectionListenerBase listener in allListeners) { if (listener.IsDiscoverable) { PeerListenerEndPoint ep = new PeerListenerEndPoint(listener.ConnectionType, listener.LocalListenEndPoint); byte[] bytes = ep.Serialize(); ms.Write(BitConverter.GetBytes(bytes.Length), 0, sizeof(int)); ms.Write(bytes, 0, bytes.Length); discoverableCount++; } } ms.Seek(16, 0); ms.Write(BitConverter.GetBytes(discoverableCount), 0, sizeof(int)); ms.Flush(); return ms.ToArray(); } }