c – 如何在winsock编程中从recv()获取确切的消息?
发布时间:2020-12-16 10:10:55 所属栏目:百科 来源:网络整理
导读:我在c中使用Winsock开发服务器客户端应用程序并遇到问题. 为了通过服务器从客户端获取消息,我使用下面的代码. int result;char buffer[200];while (true){ result = recv(client,buffer,200,NULL); if (result 0) cout "ntMessage from client: nnt" me
我在c中使用Winsock开发服务器客户端应用程序并遇到问题.
为了通过服务器从客户端获取消息,我使用下面的代码. int result; char buffer[200]; while (true) { result = recv(client,buffer,200,NULL); if (result > 0) cout << "ntMessage from client: nnt" << message << ";"; } 我从客户端向服务器发送消息“Hello”.但是缓冲区实际上是这样的: Helloììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììì 我错过了什么? 解决方法
由于recv可能没有收到你告诉它的字节数,因此通常使用一个函数
像这样接收指定的字节数.从 here修改 int receiveall(int s,char *buf,int *len) { int total = 0; // how many bytes we've received int bytesleft = *len; // how many we have left to receive int n = -1; while(total < *len) { n = recv(s,buf+total,bytesleft,0); if (n <= 0) { break; } total += n; bytesleft -= n; } *len = total; // return number actually received here return (n<=0)?-1:0; // return -1 on failure,0 on success } 如果您收到非空终止的字符串,则由null终止字符串. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |