2015-11-14 33 views
1

我用C寫的接收緩衝區包含沒有什麼預期

struct recv_packet 
{ 
    int magic; 
    int code; 
    int length; 
    char *body; 

}; 

char send_buff[1024+1] = ""; 
ZeroMemory(&send_buff, 1024); 
memset(send_buff, 'A', 1024); 
//send_buff[1024] = '\0'; 
recv_packet rcv_pkt = { 0 }; 
rcv_pkt.magic = MAGIC; 
rcv_pkt.code = 0; 
rcv_pkt.length = strlen(send_buff); 
rcv_pkt.body = send_buff; 
int size = sizeof(rcv_pkt.magic) + sizeof(rcv_pkt.code) + sizeof(rcv_pkt.length) + 1024+1; 


if (send(ClientSocket, (char *)&rcv_pkt, size, 0) == SOCKET_ERROR) 
{ 
    printf("Error %d\n", WSAGetLastError()); 
    closesocket(ClientSocket); 
    WSACleanup(); 
    return 1; 
} 

在另一邊,我抓住這個包這樣的服務器端應用程序:

public struct recv_packet 
     { 
      public int magic; 
      public int code; 
      public int length; 
      public byte[] body; 

     }; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      int port = 4000; 
      TcpClient client = new TcpClient("127.0.0.1", 4000); 
      NetworkStream nws = client.GetStream(); 
      BinaryWriter bw = new BinaryWriter(nws); 
      BinaryReader br = new BinaryReader(nws); 
      byte[] buff = new byte[512]; 

      send_packet pkt = new send_packet(); 
      pkt.magic = magic; 
      pkt.cmd = (int)command.MOVE_MOUSE; 
      while (true) 
      { 

       bw.Write(pkt.magic); 
       bw.Write(pkt.cmd); 

       //br.Read(buff, 0, 512); 
       recv_packet rcv_pkt = new recv_packet(); 
       rcv_pkt.magic = br.ReadInt32(); 
       rcv_pkt.code = br.ReadInt32(); 
       rcv_pkt.length = br.ReadInt32(); 
       rcv_pkt.body = br.ReadBytes(rcv_pkt.length); 
       //string str = rcv_pkt.length.ToString(); 
       string str = System.Text.Encoding.Default.GetString(rcv_pkt.body); 

       MessageBox.Show(str); 


      } 

     } 

因此,假設體將只有'65',但我倒了一些垃圾。

enter image description here

爲什麼會這樣呢?感謝您的時間。

回答

0

據我所知,解決這個問題的方法很少 - 其中一個方法是重新構建一點結構,然後創建一個緩衝區,其中所有結構元素將逐一安裝。所以解決方案如下所示:

char send_buff[1024+1] = ""; 
ZeroMemory(&send_buff, 1025); 
memset(send_buff, 'A', 1024); 
recv_packet *rcv_pkt = (recv_packet *)malloc(sizeof(recv_packet)+1024+1); 
//recv_packet rcv_pkt = { 0 }; 
rcv_pkt->magic = MAGIC; 
rcv_pkt->code = 0; 
rcv_pkt->length = strlen(send_buff); 
memcpy(rcv_pkt->body, send_buff, 1025); 
int size = sizeof(rcv_pkt->magic) + sizeof(rcv_pkt->code) + sizeof(rcv_pkt->length) + 1024 + 1; 
//printf("%d", size); 
//getchar(); 
//return 0; 

//if (send(ClientSocket, rcv_pkt.body, rcv_pkt.length, 0) == SOCKET_ERROR) 
if (send(ClientSocket, (char *)rcv_pkt, size, 0) == SOCKET_ERROR) 
相關問題