c ++套接字数据发送c#数据接收

时间:2015-04-01 22:48:08

标签: c# c++ sockets

我正在尝试使用从c ++ tcp socket到c#tcp socket的头文件发送一些数据。请参阅下面的代码,了解此appraoch。

发送数据的C ++代码

typedef struct tag_TCP_Header_Data{
  int iMessageID;
  int iDataLen;
  int iCheckSum;
}TCP_HEADER_DATA;

  TCP_HEADER_DATA stTcpHeader = {0};
  char acSendBuf[1024] = {0};  
  char chData[38] = "01 April - I compile my simple program";

  stTcpHeader.iMessageID  = 100;
  stTcpHeader.iDataLen    = 38;
  stTcpHeader.iCheckSum   = 190;

  memcpy(acSendBuf, &stTcpHeader, sizeof(stTcpHeader));
  memcpy(acSendBuf+sizeof(stTcpHeader), &chData, sizeof(chData));

  int iSent = SendSocketData(acSendBuf, sizeof(acSendBuf));

接收数据的C#代码

public void AddBytesFromArrayToArrayList(ref ArrayList arrayListReceivedBytes, byte[] byteReceivedBuffer, int intLength)
{
  for (int intCount = 0; intCount < intLength; intCount++)
  {
    arrayListReceivedBytes.Add(byteReceivedBuffer[intCount]);
  }
}

public byte[] ReceiveMessage()
{
  lock (this.objectToLock)
  {
    byte[] byteReceivedBuffer = new byte[1024];
    int intBytesReceived = 0;
    ArrayList arrayListReceivedBytes = new ArrayList();
    do
    {
      try
      {
        intBytesReceived = this.socket.Receive(byteReceivedBuffer, byteReceivedBuffer.Length, SocketFlags.None);
        this.AddBytesFromArrayToArrayList(ref arrayListReceivedBytes, byteReceivedBuffer, intBytesReceived);
        Thread.Sleep(100);
      }
      catch (SocketException ex)
      {
        string str = ex.Message;
      }
      catch (Exception ex)
      {
        string str = ex.Message;
      }
    }
    while (this.socket.Available > 0);
    byte[] byteReceived = (byte[])arrayListReceivedBytes.ToArray(typeof(byte));
    return byteReceived;
  }
}

服务器获取头文件数据,如下所示。我知道这个int和char字节数据转换的c#代码中缺少的东西。有人能指出我吗?

[0]  100    byte
[1]  0      byte
[2]  0      byte
[3]  0      byte
[4]  160    byte
[5]  0      byte
[6]  0      byte
[7]  0      byte
[8]  190    byte
[9]  0      byte
[10] 0      byte
[11] 0      byte

[12] Correct data
[..] Correct data
[..] Correct data

0 个答案:

没有答案