收到的tcpclient缓冲区包含的不是预期的

时间:2015-11-14 11:19:47

标签: c# client-server tcpclient

我有一个用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'但相反,我有一些垃圾。

{{3}}

为什么会发生这种情况?谢谢你的时间。

1 个答案:

答案 0 :(得分: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)