In complex network environment, the length of network messages is not always fixed. Network data packets can be divided into fixed-length data, variable-length data, sticking/unpacking, fewer/group data and so on. The term sticky packet refers to, for example, sending 500 bytes of data to the client or server at a time, but because of network delay and other reasons, the server may receive two messages at a time, that is, 1000 bytes, that is, network data packets stick together, so a process of unpacking is needed; subpackage refers to, for example, sending 1000 bytes at a time. Data, when the server receives, it receives only 500 bytes of data at first, then the server will have to wait for the remaining data to be transmitted before processing.
In order to make the program better adapt to different data lengths, you can modify the server-side code and use datalength to identify the current data length.
//6. Processing requests switch (header->cmd) { case CMD_LOGIN: { recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0); Login* login = (Login*)szRecv; //Receive the client's login information, here we need to pay attention to remove the headerd part, so add data offset, and read the scope to subtract the size of the header. printf("receive message: CMD_LOGIN, data length:%d, username:%s, password: %s\n", login->dataLength, login->UserName, login->PassWord); //Prompt for an order //Assuming that the user enters correctly (ignoring the validation process for correct username and password) LoginResult inret; //7. send data to client send(_cSock, (char*)&inret, sizeof(LoginResult), 0); //Send login results to clients } break; case CMD_LOGOUT: { recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0); LogOut* logout; printf("receive message: CMD_LOGIN, data length:%d, username:%s\n", logout->dataLength, logout->UserName); LogoutResult outret; //7. send data to client send(_cSock, (char*)&outret, sizeof(LogoutResult), 0); } break; default: { DataHeader header = {0, CMD_ERROR}; send(_cSock, (char*)&header, sizeof(DataHeader), 0); } break; }