views:

40

answers:

2

I have a portion of C code that I am trying to port over to C#.

In my C code, I create a socket and then issue a receive command. The receive command is

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

Now, the command buffer is returned with new values including command_buffer[8] being a pointer to a string.

I'm really confused as to how to do this in .NET because the .NET Read() method specifically takes in bytes and not char. The important part is that I get the pointer to the string.

Any ideas?

A: 

C# makes a distinction between byte arrays and Unicode strings. A byte is an unsigned 8-bit integer, while a char is a Unicode character. They are not interchangeable.

The equivalent of recv is Socket.Receive. You allocate memory in form of a managed byte array and pass it to the Receive method which will fill the array with the received bytes. There are no pointers involved (just object references).

Socket mysocket = // ...;

byte[] commandBuffer = new byte[8];
socket.Receive(commandBuffer);
dtb
+1  A: 

Socket Send and Receive C#

Socket.Receive method

Receive method receives data from a bound Socket to your buffer. The method returns number of received bytes. If the socket buffer is empty a WouldBlock error occurs. You should try to receive the data later.

Following method tries to receive size bytes into the buffer to the offset position. If the operation lasts more than timeout milliseconds it throws an exception.

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) { /* ... */ }
abmv
+1 for using an Encoding to translate from byte[] to string, which (I believe) is actually the answer to the question. Everything else is extra. 8 )
Task