public bool Send(MessagePayload msg) { lock (this) { if (!this.TcpClient.Connected) { Env.Print("unconnected,message not sent:" + msg); return(false); } var headerBytes = msg.Header.GetBytes(); TcpClient.GetStream().Write(headerBytes, 0, headerBytes.Length); try { var dataHandler = msg as IDataHandler; dataHandler?.Transfer(TcpClient.GetStream()); } catch (Exception ex) { OnDisconnected(ex); return(false); } OnSentCompleted(msg); return(true); } }
public void Stop() { server.Stop(); Listening = false; Env.Print("listening stoped"); ListeningStoped?.Invoke(this, server); }
public async void ListenAsync(string ip, int port) { if (Listening) { throw new Exception("Listening"); } Listening = true; server = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port); server.Start(); ListeningStarted(this, server); Env.Print($"listening: {server.LocalEndpoint.ToString()}"); try { while (true) { Env.Print("waiting for a connection"); var client = await server.AcceptTcpClientAsync(); Env.Print("one incoming tcp connection"); var session = new TcpClientSession(client); NewSession.Invoke(this, session); TcpClientAccepted?.Invoke(this, session); session.Receive(); } } catch (Exception ex) { Env.Print(ex.Message); } }
private void OnDisconnected(Exception ex) { if (disconnected) { Env.Print("warn:connection hase been disconnected before."); return; } disconnected = true; Env.Print($"disconnected from {this.RemoteEndPoint}.cause:{ex.Message}"); this.TcpClient.Close(); this.TcpClient.Dispose(); Disconnected?.Invoke(this, this); }
private void ReadHeader(NetworkStream networkStream) { Byte[] bytes = new byte[Header.HEADER_SIZE]; var readSize = 0; while (readSize != bytes.Length) { readSize += networkStream.Read(bytes, 0, Header.HEADER_SIZE - readSize); } var header = Header.GetHeader(bytes); Env.Print($"read header {header}"); var messagepayload = GetMessagePayload(header.Key, header); var dataHandler = messagepayload as IDataHandler; dataHandler?.Receive(networkStream); OnReceived(messagepayload); }
public async void Connect() { try { Client = new System.Net.Sockets.TcpClient(new IPEndPoint(IPAddress.Parse(IpAddressHelper.GetHostIp()), new Random().Next(80, 6000))); Env.Print($"connecting to {this.Ip}:{this.Port}"); await Client.ConnectAsync(IPAddress.Parse(this.Ip), this.Port); Env.Print($"connected to {Client.Client.RemoteEndPoint} from {Client.Client.LocalEndPoint}"); Session = new TcpClientSession(Client); NewSession(this, Session); Session.Disconnected += Disconnected; Connected?.Invoke(this, Session); Session.Receive(); } catch (Exception ex) { Env.Print($"connect failed.cause:{ex.Message}"); ConnectFailed(this, ex); } }
private void OnSentCompleted(MessagePayload messagePayload) { Env.Print("sent " + messagePayload.ToString()); SentCompleted?.Invoke(this, messagePayload); }
private void OnReceived(MessagePayload messagePayload) { Env.Print($"read:{messagePayload.ToString()}"); Received?.Invoke(this, messagePayload); }