1

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

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

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

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

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

有任何想法吗?

4

2 回答 2

2

套接字发送和接收 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) { /* ... */ }
于 2010-05-20T13:55:24.633 回答
0

C# 区分字节数组和 Unicode 字符串。一个字节是一个无符号的 8 位整数,而一个字符是一个 Unicode 字符。它们不可互换。

等价recvSocket.Receive 。您以托管字节数组的形式分配内存并将其传递给 Receive 方法,该方法将用接收到的字节填充数组。不涉及指针(只是对象引用)。

Socket mysocket = // ...;

byte[] commandBuffer = new byte[8];
socket.Receive(commandBuffer);
于 2010-05-20T13:52:28.183 回答