Constructing and sending binary data over network

后端 未结 3 1650
走了就别回头了
走了就别回头了 2020-12-15 15:05

I am creating a command-line client for minecraft. There is a full spec on the protocol that can be found here: http://mc.kev009.com/Protocol. To answer your question before

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 15:31

    off the top of my head...

    const char* s;  // the string you want to send
    short len = strlen(s);
    
    // allocate a buffer with enough room for the length info and the string
    char* xfer = new char[ len + sizeof(short) ];
    
    // copy the length info into the start of the buffer
    // note:  you need to hanle endian-ness of the short here.
    memcpy(xfer, &len, sizeof(short));
    
    // copy the string into the buffer
    strncpy(xfer + sizeof(short), s, len);
    
    // now xfer is the string you want to send across the wire.
    // it starts with a short to identify its length.
    // it is NOT null-terminated.
    

提交回复
热议问题