socket-awaitable icon indicating copy to clipboard operation
socket-awaitable copied to clipboard

Receive Timeout seem not working

Open Airitam opened this issue 8 years ago • 1 comments

Hi,

I tried to apply SocketAwaitable as a Socket Client by send & receive data to Server with 5 seconds receive timeout , below is code i using

        using (var client = new Socket(SocketType.Stream, ProtocolType.Tcp))
        {
            client.ReceiveTimeout = 5000;

            using (var connectAwaitable = new SocketAwaitable())
            {
                connectAwaitable.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_remoteIP), _remotePort);
                var connectResult = await client.ConnectAsync(connectAwaitable);
            }

            // Send.
            using (var sendAwaitable = new SocketAwaitable())
            {
                sendAwaitable.Buffer = new ArraySegment<byte>(data);

                var sendResult = await client.SendAsync(sendAwaitable);
            }

            using (var recvAwaitable = new SocketAwaitable())
            {
                recvAwaitable.Buffer = new ArraySegment<byte>(new byte[512]);
                var respResult = await client.ReceiveAsync(recvAwaitable);

                if (respResult == SocketError.Success)
                {
                    response = recvAwaitable.Transferred.Array;
                }
            }
        `}`

I tried to set server side to response socket client after 10 seconds but my socket client never throw Socket Timeout exception. Could you help to advice?

Airitam avatar Oct 30 '16 09:10 Airitam

If you read carefully the documentation, Socket.ReceiveTimeout only covers sync calls,

https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.receivetimeout(v=vs.110).aspx

For async calls, if you want a timeout, you should use other mechanisms, such as Task.WaitAny(client.ReceiveAsync(recvAwaitable), Task.Delay(5000)). However, the side effect is that you have to close the socket so as to actually stop ReceiveAsync.

Of course, it goes beyond the scope of this library.

lextm avatar Jul 09 '17 03:07 lextm