NetCoreServer
NetCoreServer copied to clipboard
Task-based TCP sockets
I am trying to use the TCP session class together with the my own service layer which is based on the async/await pattern (all functions of the service layer return Tasks), is there any implementation of the TCP Session that is compatible with async/await (so far I've seen that OnReceived returns only void)
Task are slower than event model on which NetCoreServer is based. But it's not difficult to build Tasks-based server/client on top of NetCoreServer using TaskCompletionSource<TResult>:
// Client requests cache fields
private Dictionary<Guid, TaskCompletionSource<SimpleResponse> _requestsByIdSimpleResponse;
public Task<SimpleResponse> Request(SimpleRequest value)
{
TaskCompletionSource<SimpleResponse> source = new TaskCompletionSource<SimpleResponse>();
Task<SimpleResponse> task = source.Task;
// Register the request
if (Send(value))
_requestsByIdSimpleResponse.Add(value.id, new Tuple<DateTime, TimeSpan, TaskCompletionSource<global::com.chronoxor.simple.SimpleResponse>>(Timestamp, timeout, source));
else
source.SetException(new Exception("Send request failed!"));
return task;
}
public bool OnReceiveResponse(SimpleResponse response)
{
if (_requestsByIdSimpleResponse.TryGetValue(response.id, out TaskCompletionSource<global::com.chronoxor.simple.SimpleResponse source))
{
source.SetResult(response);
_requestsByIdSimpleResponse.Remove(response.id);
return true;
}
return false;
}