/// <summary> /// Starts the server class so clients can connect to it /// </summary> public void Start() { try { listener = new TcpListener(IPAddress.Any, port); listener.Start(); Listen(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); form.AddMessage("[client]: Another server is already running!"); form.SetButtons(true, true); } }
/// <summary> /// Starts a loop that listens for new messages /// </summary> /// <param name="rClient"></param> private void ReceiveData(Client rClient) { byte[] buffer = new byte[BufferSize]; var stringBuilder = new StringBuilder(); string message; form.AddMessage("[client]: Connected!"); using (NetworkStream ns = rClient.Connection.GetStream()) { while (listening) { do { int readBytes = ns.Read(buffer, 0, BufferSize); stringBuilder.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, readBytes)); } while (ns.DataAvailable); message = stringBuilder.ToString(); stringBuilder.Clear(); // When server disconnects, stop listening if (message.StartsWith("@close")) { form.AddMessage("[server]: Host disconnected"); break; } if (!string.IsNullOrEmpty(message)) { form.AddMessage(message); } } form.SetButtons(true, true); } }