What is the best way to handle clients using TCPListener?

I had a problem with too many connections . After several tests, I read the problem with the MY server. The fact that the server port for listening was on the left side should have told me.

When I run the same client code using a server on another computer, I do not open hundreds of ports. When my server on my local computer I get> 200, it connects to my listening port. I think that I am mistreating clients. My code below with all remote server and client code

{
    TcpListener server = null;
    server = new TcpListener(port);
    server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
    server.Start();

    while (true)
    {
        var client = server.AcceptTcpClient();
        using(var stream = client.GetStream()) {
        ...
        stream.Read(...
        ...
        stream.Write(...
        } //using above should close this.
        client.Close();
    }
    server.Stop();
}

I changed the code to use asynchronous connections and it blocks the second time it does stream.Read only under while (client.Connected)

    server = new TcpListener(port);
    server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
    server.Start();
    server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), server);
    while (true)
        Thread.Sleep(1000); //infinite loop for testing




public void DoAcceptTcpClientCallback(IAsyncResult ar)
{
    Byte[] bytes = new Byte[1024 * 4];
    TcpListener listener = (TcpListener)ar.AsyncState;
    using (TcpClient client = listener.EndAcceptTcpClient(ar))
    {
        using (var stream = client.GetStream())
        using (var ostream = new MemoryStream())
        {
            while (client.Connected)
            {
                int i;
                while ((i = stream.Read(bytes, 0, bytes.Length)) == bytes.Length)
                    ostream.Write(bytes, 0, i);

                ostream.Write(bytes, 0, i);
                szresults = Func(ostream)
                var obuf = Encoding.UTF8.GetBytes(szresults);
                stream.Write(obuf, 0, obuf.Length);
            }
        }
        client.Close();
    }
}
+3
2

. , . - .

, - , , , IME. , .

- , , , . , , , .

, TcpClient using, , , - . , , , using.

+2

socket.shutdown s ocket.close. , , - .

, . 5 .

,

0

Source: https://habr.com/ru/post/1756116/


All Articles