tags:

views:

451

answers:

3
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? Ы

+2  A: 

Set this property before you call socket.Receive(...). From MSDN

socket.ReceiveTimeout = 1000;
Jason Punyon
it does not work
A: 

According to this MS article, you need to call Accept before Receive and Connect before Send.

Mark
I called Connect and with Accept it doesnt work too. With some servers it works, but if a server is slow program stops.
What do you mean the server is slow the program stops? I thought you wanted it to quit after some timeout has elapsed? Can you post some more detail in your main post (e.g.: all connection code)?
Mark
+2  A: 
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();
}
Sekhat