.NET Async TcpListener / TcpClient Question

I lost a little how to properly implement asynchronous methods for TcpListner and TcpClient int.NET. I read quite a lot of listening messages, and I believe that I have code to receive new clients on the server. Here is the code for accepting new connections:

Public Sub Start()
    m_oListener = New TcpListener(m_oIpAddress, m_iPort)

    m_oListener.Start()
    m_oListener.BeginAcceptTcpClient(New AsyncCallback(AddressOf OnAcceptClient), m_oListener)
End Sub

Public Sub OnAcceptClient(ByVal ar As IAsyncResult)
    Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
    Dim client As TcpClient = listener.EndAcceptTcpClient(ar)

    If listener.Server.IsBound Then
        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf OnHandleClient), client)
        listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf OnAcceptClient), listener)
    End If
End Sub

I am not sure what to do with the client after the connection is established. From what I saw, usually people create a new thread for each client connected to prevent reading IO from blocking the application.

My application will have up to 100 clients connected at any given time. If I unscrew a new thread for each client, then I will have about 100 threads. It's right? I think I just missed something using asynchronous methods in the .NET framework.

, , , (, " " ), . , .

.

+3
2

TcpClient OnAcceptClient, NetworkStream GetStream, BeginRead ( BeginWrite), . BeginRead , EndRead , TcpListener.

+2

100 , , . , -.

, , .

, , .

:

foreach TcpClient
    if DataAvailable
        BeginRead()
+1

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


All Articles