Reputation:
Socket socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
...
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
...
socket.Send(bytesSent, bytesSent.Length, 0);
...
bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
After socket has sent the data, server does not respond so that program waits for response. How to stop receiving data after 1000 miliseconds? Ы
Upvotes: 2
Views: 2977
Reputation: 121
Instead of relyinging on the Socket.ReceiveTimeout to do the job, you can use Socket.Poll(). Using the ReceiveTimeout will throw an exception when a timeout occur, while Poll() does not. You will now be able to handle a timeout in a more graceful way.
var received = -1;
var receiveBuffer = new byte[_receiveBufferSize];
// The poll will timeout after 5 seconds (Defined in microseconds)
var canRead = _socket.Poll(5000000, SelectMode.SelectRead);
if(canRead)
received = _socket.Receive(receiveBuffer);
if (received > 0)
{
// Parse the buffer
}
else
{
// Do other stuff
}
Upvotes: 1
Reputation: 4489
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.RecieveTimeout = 1000;
socket.SendTimeout = 1000;
// Not needed
// socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
IPAddress ipAddress = IPAddress.Parse("192.168.2.2");
int port = 9000;
try
{
// could take 15 - 30 seconds to timeout, without using threading, there
// seems to be no way to change this
socket.Connect(ipAddress, port);
// Thanks to send timeout this will now timeout after a second
socket.Send(bytesSent, bytesSent.Length, 0);
// This should now timeout after a second
bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
}
finally
{
socket.Close();
}
Upvotes: 2
Reputation: 468
According to this MS article, you need to call Accept before Receive and Connect before Send.
Upvotes: 0