gpt4 book ai didi

c# - .NET 相当于 recv?

转载 作者:行者123 更新时间:2023-12-03 12:01:40 27 4
gpt4 key购买 nike

我有一部分 C 代码正在尝试移植到 C#。

在我的 C 代码中,我创建了一个套接字,然后发出一个接收命令。接收命令是

void receive(mysocket, char * command_buffer)
{
recv(mysocket, command_buffer, COMMAND_BUFFER_SIZE, 0);
}

现在,命令缓冲区返回新值,包括 command_buffer[8]作为指向字符串的指针。

我真的很困惑如何在 .NET 中执行此操作,因为 .NET Read() 方法专门接收字节而不是字符。重要的部分是我得到了指向字符串的指针。

有任何想法吗?

最佳答案

Socket Send and Receive C#

Socket.Receive 方法

Receive 方法从绑定(bind)的 Socket 接收数据到您的缓冲区。方法
返回接收的字节数。如果套接字缓冲区为空
会发生错误。您应该尝试接收
以后的数据。

以下方法尝试将 size 字节接收到缓冲区中以
偏移位置。如果操作持续时间超过超时
毫秒它会引发异常。

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) { /* ... */ }

关于c# - .NET 相当于 recv?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2874297/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com