public Connection(TcpClient tc) { // ConnectionID = 99; if (tc != null) { TcpClnt = tc; } else { //print some error to logger throw new Exception("NullReference"); } if (tc.Connected) { //Logger.Print("ctor:Connection, LocalEndPoint=" + tc.Client.LocalEndPoint.ToString()); //Logger.Print("ctor:Connection, RemoteEndPoint=" + tc.Client.RemoteEndPoint.ToString()); ValidateNStoreIPandPort(tc.Client.LocalEndPoint.ToString()); // since this constructor assumes TcpClient is delivered on call, // it now initializes the Stream variables accordingly // after connected , initialize strem and r\w bin.formatter or serialization objects Stream = TcpClnt.GetStream(); BinFormatter = new BinaryFormatter(); } }
public void ConnectToServer(IPEndPoint EP) { if (!TcpClnt.Connected) { TcpClnt.Connect(EP); Logger.Print("INFO: ConnectToserver succeeded to " + EP.Address.ToString() + ":" + EP.Port); // after connected , initialize strem and r\w bin.formatter or serialization objects Stream = TcpClnt.GetStream(); BinFormatter = new BinaryFormatter(); } else { // add code for: // 1) throw error that connection is already active // or // 2) disconnect old connection and reconnect to new address } }
public void WaitForMessages() { try { while (TcpClnt.Connected) { if (Stream != null) { object obj = BinFormatter.Deserialize(Stream); if (obj is ChatMessage && GotMessageEv != null) { GotMessageEv(this, new MessageEventArgs((ChatMessage)obj)); //Logger.Print("got msg: " + ((Message)obj)); } else { // print warning , got strange input (not Message) on incomming stream } } else { // print warning , incomming stream is null cant read messages Logger.Print("Warning:incomming stream is null cant read messages"); } } } catch (Exception e) { Logger.Print("Error: Connection fail on WaitForMessages with exp.info: " + e.Message); //Logger.Print("INFO: stream is null="+ (Stream==null) ); //Logger.Print("INFO: GotMessage=" + (GotMessage).ToString()); TcpClnt.Close(); // throw e; if (ConnectionClosedEv != null) { ConnectionClosedEv(this, new ConnectionEventArgs(this)); } } }
public void Close() { TcpClnt.Close(); }