没有在客户端Winsock中接收完整数据

时间:2016-04-12 08:50:31

标签: c++ serialization winsock

我在发送数据时遇到winsock客户端服务器的问题。我有一个包含用户名作为主键的地图,以及每个用户的消息向量(存储在结构中): map<std::string,std::vector<message *> > data;

struct message{
        static unsigned int last_id;
        unsigned int id;
        std::string baa;
        std::string timestamp;
    }

我还有一个序列化程序,以便通过Winsock将其发送到客户端(只接受字符数组)

class MessageSerializer
{
public:
    MessageSerializer(const message& messageStruct)
    : m_msgRef(messageStruct)
    , m_msgLength(m_msgRef.msg.length())
    , m_timeLength(m_msgRef.timestamp.length())
    {}

    size_t RequiredBufferSize() const
    {
        return sizeof(int) + sizeof(size_t)*2 + m_msgLength + m_timeLength;
    }

    void Serialize(void* buffer) const
    {
        PushNum     (buffer, m_msgRef.id);
        PushString  (buffer, m_msgRef.msg.c_str(), m_msgLength);
        PushString  (buffer, m_msgRef.timestamp.c_str(), m_timeLength);
    }
private:
    const message&  m_msgRef;
    const size_t    m_msgLength;
    const size_t    m_timeLength;

    template<typename INTEGER>
    void PushNum(void*& buffer, INTEGER num) const
    {
        INTEGER* ptr = static_cast<INTEGER*>(buffer);
        //copying content
        *ptr = num;
        //updating the buffer pointer to point the next position to copy
        buffer = ++ptr;
    }
    void PushString(void*& buffer, const char* cstr, size_t length) const
    {
        PushNum(buffer, length);
        //copying string content
        memcpy(buffer, cstr, length);
        //updating the buffer pointer to point the next position to copy
        char* ptr = static_cast<char*>(buffer);
        ptr += length;
        buffer = ptr;
    }
}

为了实现这个序列化器,我做了以下内容:

message msg_cpy=*data[recvbuf_usrn].at(0);
MessageSerializer serializer(msg_cpy);
char* buffer = new char[serializer.RequiredBufferSize()];
serializer.Serialize(buffer);

发送时间戳时出现问题。在msg_cpy中我正确存储了数据(例如id = 1,msg = hello,timestamp = 2016-04-02 10:40:45),但在发送数据时,时间戳只保存前三个值,也就是说,在客户端中,我在反序列化id = 1,msg = hello,timestamp = 201后跟垃圾后收到。我知道问题存在于服务器中,我推断它可以是序列化功能(唯一的其他选择可能是Winsock的&#34; send&#34;功能)。但它可能有什么问题呢?如果我写了一个msg = 2016-04-02 10:40:20,我会在客户端收到。

感谢任何帮助

1 个答案:

答案 0 :(得分:1)

您展示的代码是正确的。错误是您未显示的代码。

通过2个课程messageMessageSerializer,我尝试了这个简单的测试:

int main() {
    message msg = {1, "foo", "2016-04-02 10:40:20" };

    MessageSerializer msgSer(msg);

    size_t sz = msgSer.RequiredBufferSize();
    char * buffer = new char[sz];
    msgSer.Serialize(static_cast<void *>(buffer));
    for (int i=0; i<sz; i++) {
        std::cout << buffer[i] << " (" << std::hex << static_cast<unsigned int>(buffer[i]) << ") ";
    }
    std::cout << std::endl;
    delete[] buffer;
    return 0;
}

结果符合预期

 (1)  (0)  (0)  (0)  (3)  (0)  (0)  (0) f (66) o (6f) o (6f)  (13)  (0)  (0)  (0) 2 (32) 0 (30) 1 (31) 6 (36) - (2d) 0 (30) 4 (34) - (2d) 0 (30) 2 (32)   (20) 1 (31) 0 (30) : (3a) 4 (34) 0 (30) : (3a) 2 (32) 0 (30)