简体   繁体   中英

Problem with sockets in C#

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

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();
}

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

socket.ReceiveTimeout = 1000;

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
}

根据此MS文章 ,您需要在接收之前调用“接受”,在发送之前调用“连接”。

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