套接字发送和接收 C#
Socket.Receive 方法
Receive 方法从绑定的 Socket 接收数据到您的缓冲区。该方法返回接收到的字节数。如果套接字缓冲区为空,则会发生 WillBlock 错误。您应该稍后尝试接收数据。
以下方法尝试将 size 字节接收到缓冲区的偏移位置。如果操作持续时间超过 timeout 毫秒,则会引发异常。
public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int received = 0; // how many bytes is already received
do {
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timeout.");
try {
received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably empty, wait and try again
Thread.Sleep(30);
}
else
throw ex; // any serious error occurr
}
} while (received < size);
}
Call the Receive method using code such this:
[C#]
Socket socket = tcpClient.Client;
byte[] buffer = new byte[12]; // length of the text "Hello world!"
try
{ // receive data with timeout 10s
SocketEx.Receive(socket, buffer, 0, buffer.Length, 10000);
string str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
}
catch (Exception ex) { /* ... */ }