private async void InitListener() { var tcpServer = new TcpListener(IPAddress.Any, ServerListenerPort); tcpServer.Start(); while (true) { var client = await tcpServer.AcceptTcpClientAsync(); var clientIp = ((IPEndPoint)client.Client.RemoteEndPoint).Address; tcpClient = new TcpClient(); tcpClient.Connect(new IPEndPoint(clientIp, ClientListenerPort)); Invoke(new Action( () => { lbConnectionStatus.Text = $"Подключен к {clientIp}"; btnSend.Enabled = true; })); var stream = client.GetStream(); while (true) { var message = TcpUtils.ReadMessage(stream); if (string.IsNullOrEmpty(message)) { Invoke(new Action( () => { lbConnectionStatus.Text = "Не подключен"; btnSend.Enabled = false; })); break; } message = DateTime.Now.ToString("t") + ": " + message; lbMessages.Invoke(new Action(() => lbMessages.Items.Add(message))); } } }
private async void InitListener() { var tcpServer = new Sockets.TcpListener(IPAddress.Any, ClientListenerPort); tcpServer.Start(); while (true) { tcpReciever = await tcpServer.AcceptTcpClientAsync(); var stream = tcpReciever.GetStream(); properlyDisconnected = false; while (true) { var message = TcpUtils.ReadMessage(stream); if (string.IsNullOrEmpty(message)) { if (!properlyDisconnected) { Invoke(new Action(() => { MessageBox.Show(this, "Соединение с сервером потеряно. Подключение будет закрыто", "Сервер отключен", MessageBoxButtons.OK, MessageBoxIcon.Information); Disconnect(); })); } break; } message = DateTime.Now.ToString("t") + ": " + message; lbMessages.Invoke(new Action(() => lbMessages.Items.Add(message))); } } }