我有一部分C代码,我试图移植到C#。
在我的C代码中,我创建一个套接字然后发出一个接收命令。接收命令是
void receive(mysocket, char * command_buffer)
{
recv(mysocket, command_buffer, COMMAND_BUFFER_SIZE, 0);
}
现在,命令缓冲区返回新值,包括command_buffer[8]
是指向字符串的指针。
我真的很困惑如何在.NET中执行此操作,因为.NET Read()方法特别采用字节而不是char。重要的是我得到了指向字符串的指针。
有什么想法吗?
答案 0 :(得分:2)
Socket.Receive方法
Receive方法从绑定的Socket接收数据到缓冲区。方法 返回接收的字节数。如果套接字缓冲区为空a 发生了WouldBlock错误。你应该试着收到 数据以后。
以下方法尝试将大小字节接收到缓冲区中 偏移位置。如果操作持续超过超时 它抛出一个异常毫秒。
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) { /* ... */ }
答案 1 :(得分:0)
C#区分字节数组和Unicode字符串。字节是无符号的8位整数,而char是Unicode字符。它们不可互换。
相当于recv
是Socket.Receive。您以托管字节数组的形式分配内存,并将其传递给Receive方法,该方法将使用接收的字节填充数组。没有涉及指针(只是对象引用)。
Socket mysocket = // ...;
byte[] commandBuffer = new byte[8];
socket.Receive(commandBuffer);