简体   繁体   English

如何使用 c++ 在 Winsock 中将大字符串从客户端发送到服务器

[英]How send big string in winsock using c++ from client to server

I am writing a server-client application using Winsock in c++ for sending a file line by line and I have a problem in sending huge string.我正在使用 c++ 中的 Winsock 编写服务器-客户端应用程序,用于逐行发送文件,但在发送大字符串时遇到问题。 The line size is very huge.线的大小非常大。

For getting the message from the client by the server I use the code below.为了让服务器从客户端获取消息,我使用下面的代码。

int result;
char message[200];

while (true)
{
    recv(newSd, (char*)&message, sizeof(message), 0);

    cout << "The Message from client: " << message << ";";
}

The above code working fine if I send small length of the message.如果我发送小长度的消息,上面的代码工作正常。 But, what I wanted is to send an unknown size of lines in a file.但是,我想要的是在文件中发送未知大小的行。

How to send a big unknown string instead of char message[200];如何发送一个大的未知字符串而不是char 消息[200];

TCP is a byte stream, it knows nothing about messages or lines or anything like that. TCP 是一个字节 stream,它对消息或行或类似的东西一无所知。 When you send data over TCP, all it knows about is raw bytes, not what the bytes represent.当您通过 TCP 发送数据时,它所知道的只是原始字节,而不是字节代表的内容。 It is your responsibility to implement a messaging protocol on top of TCP to delimit the data in some meaningful way so the receiver can know when the data is complete.您有责任在 TCP 之上实现消息传递协议,以某种有意义的方式分隔数据,以便接收者知道数据何时完成。 There are two ways to do that:有两种方法可以做到这一点:

  • send the data length before sending the actual data.在发送实际数据之前发送数据长度。 The receiver reads the length first, then reads however many bytes the length says.接收器首先读取长度,然后读取长度表示的字节数。

  • send a unique terminator after sending the data.发送数据后发送唯一的终止符。 Make sure the terminator never appears in the data.确保终止符永远不会出现在数据中。 The receiver can then read until the terminator is received.然后接收器可以读取,直到接收到终止符。

You are not handling either of those in your recv() code, so I suspect you are not handling either of them in your send() code, too (which you did not show).您没有在recv()代码中处理其中任何一个,所以我怀疑您也没有在send()代码中处理它们中的任何一个(您没有显示)。

Since you are sending a text file, you can either:由于您要发送文本文件,因此您可以:

  • send the file size, such as in a uint32_t or uint64_t (depending on how large the file is), then send the raw file bytes.发送文件大小,例如uint32_tuint64_t (取决于文件的大小),然后发送原始文件字节。

  • send each text line individually as-is, terminated by a CRLF or bare-LF line break after each line, and then send a final terminator after the last line.按原样单独发送每个文本行,在每行之后以CRLFbare-LF换行符终止,然后在最后一行之后发送最终终止符。

You are also ignoring the return value of recv() , which tells you how many bytes were actually received.您还忽略了recv()的返回值,它告诉您实际收到了多少字节。 It can, and usually does, return fewer bytes than requested, so you must be prepared to call recv() multiple times, usually in a loop, to receive data completely.它可以而且通常确实返回的字节数少于请求的字节数,因此您必须准备好多次调用recv() ,通常是在一个循环中,以完全接收数据。 Same with send() .send()相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM