public static byte[] GetNetworkBytes(NetworkData data) { using (var stream = new MemoryStream()) { formatter.Serialize(stream, data); return(stream.ToArray()); } }
public bool IsOnline() { try { var testData = NetworkData.GetNetworkBytes(new NetworkData(DataType.Heartbeat, null)); networkStream.Write(testData, 0, testData.Length); return(true); } catch (Exception) { Disconnect(); return(false); } }
private void InitializeClient() { Connected = true; networkStream = client.GetStream(); ConnectionChecker = new Thread(e => { while (Connected) { if (!IsOnline()) { Disconnect(); break; } Thread.Sleep(500); } }) { IsBackground = true }; ConnectionChecker.Start(); thread = new Thread(e => { while (Connected) { if (!client.Connected && !IsOnline()) { Disconnect(); break; } if (client.Available <= 0) { continue; } lock (networkStream) { var data = new byte[client.Available]; networkStream.Read(data, 0, data.Length); var networkdata = NetworkData.GetNetworkData(data); if (networkdata.DataType != DataType.Heartbeat) { MessageArrivedEvent?.Invoke(this, networkdata.Data); } } } }); thread.IsBackground = true; thread.Start(); }
public void Send(byte [] data) { if (!Connected) { return; } try { var networkdata = new NetworkData(DataType.Normal, data); var sendingdata = NetworkData.GetNetworkBytes(networkdata); networkStream.Write(sendingdata, 0, sendingdata.Length); } catch { Disconnect(); } }