简体   繁体   中英

Write high-scalable socket server using SocketAsyncEventArgs

Okay, I read many questions involving writing high scale-able servers but I never really came across a good answer. Anyway I want to create a high scale-able clients, which handles lots of data and connections. What I created was a simple client using SocketAsyncEventArgs and C#5 async/await like this:

public async Task<int> SendAsync(byte[] buffer, int offset, int size)
{
    var socketArgs = new SocketAsyncEventArgs();
    var tcs = new TaskCompletionSource<int>();

    socketArgs.SetBuffer(buffer, offset, size);
    socketArgs.Completed += (sender, args) =>
    {
        tcs.SetResult(socketArgs.BytesTransferred);
        LastSocketError = socketArgs.SocketError;
    };

    if (_clientSocket.SendAsync(socketArgs)) 
        return await tcs.Task;

    LastSocketError = socketArgs.SocketError;
    return socketArgs.BytesTransferred;
}

And that for ConnectAsync, ReceiveAsync and AcceptAcync. This works great for the client part, but on my server I don't know how to get it right.. (I would end up creating a Thread for every Client for receiving.) I can use the APM (Begin/End) or using EventHandler but that kills the purpose of using async/await and in the end it isn't memory efficient when creating a new SocketAsyncEventArgs for every call. I tried creating a Pool (using a ConcurrentBag) but then I still had to create a TaskCompletionSource over and over (as you can use it only once.)

So I don't think this is a good idea of creating this, although I really like it.. What would be a good design to create a high scale-able and high performance server?

We could, of course, adjust such asynchronous methods with the task, but that would largely defeat the purpose of these methods, similar to the assignment of an IAsyncResult in the case of APM. However, even so, we want to be able to take advantage of the async / await support of the compiler to facilitate the writing of asynchronous code using sockets. We want our cake and eat it too. Of course, the compiler admits expecting more than Tasks. So, if you have a specialized scenario like this, you can take advantage of the support based on compiler patterns to wait for things. More information: https://blogs.msdn.microsoft.com/pfxteam/2011/12/15/awaiting-socket-operations/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM