Hello. I want to make on the basis of just a permanent connection between the client and the server. But many questions arise. As I understand it, TcpListener in wiretapping mode allows you to get a TcpClient with which you can directly interact? But after connecting and messaging it closes. And I need to maintain an active connection, moreover, on the side of both the client and the server, to respond to every new message that comes from either side.

public class Server { private TcpListener serverListener = null; private NetworkCredential authCredential = null; private int port; public TcpClient client = null; public Server(int port, string userName, string password) { authCredential = new NetworkCredential(userName, password); this.port = port; } public async void StartServer() { IPAddress serverIp = IPAddress.Any; serverListener = new TcpListener(serverIp, port); serverListener.Start(); while (true) { try { using (client = await serverListener.AcceptTcpClientAsync()) { using (NetworkStream networkStream = client.GetStream()) { using (StreamReader streamReader = new StreamReader(networkStream, Encoding.UTF8, false,2048, true)) { string receivedMessage = streamReader.ReadToEndAsync(); } using (StreamWriter writer = new StreamWriter(networkStream)) { writer.Write("какой-то текст"); } } } } catch { } } } } 
  • one
    It is closed, because using (client = await serverListener.AcceptTcpClientAsync ()) - and why close it immediately, if you still need it? Got a customer, saved and communicate on his stream. - Alexander Alexeev
  • Thanks, I already understood one error, using (network stream ...) is released by the client itself. Now there is a permanent connection. How to make it clear now to both the client and the server that they received a message? Or do I periodically at the client level just check if there is something from the server? - Morgomirius
  • The only way to understand that something has come is to constantly read from the stream that gives TcpClient. It is possible asynchronously, and it is possible blocking. - Alexander Alexeev
  • That is, in real applications, online games, too, there is a constant check in this way, or can there be anything that the client can notify and that a message has come to him? Maybe not a socket, but something else? - Morgomirius
  • There is no message concept in streams - data just flows. The message is the essence of the application, and the business of the application correctly mars the message to / from the stream. Again - ReadAsync for asynchronous read - is this a permanent check? I once wrote a client - you can look for an example of how the lines are read from the stream. I will not say about real applications - I heard that they generally communicate via UDP, but by streams or datagrams - I pass. - Alexander Alexeev

0