[英]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);
套接字發送數據后,服務器不響應,因此程序等待響應。 如何在1000毫秒后停止接收數據? Ы
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();
}
在調用socket.Receive(...)之前,請設置此屬性。 從MSDN
socket.ReceiveTimeout = 1000;
您可以使用Socket.Poll()來代替依賴Socket.ReceiveTimeout的工作。 當發生超時時,使用ReceiveTimeout會引發異常,而Poll()不會。 現在,您將能夠以更優雅的方式處理超時。
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文章 ,您需要在接收之前調用“接受”,在發送之前調用“連接”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.