在套接字中发送多个发送/接收 [英] sending multiple send/recv in socket

查看:41
本文介绍了在套接字中发送多个发送/接收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于在套接字程序中使用多个发送/接收,我需要澄清一下.我的客户端程序如下所示(使用 TCP SOCK_STREAM).

I need bit clarification on using multiple send/recv in socket programs. My client program looks below(Using TCP SOCK_STREAM).

    send(sockfd,"Messgfromlient",15,0);
    send(sockfd,"cli1",5,0);
    send(sockfd,"cli2",5,0);
    send(sockfd,"cli3",5,0);
    send(sockfd,"cli4",5,0);
    send(sockfd,"cli5",5,0);

服务器程序如下所示.

    recv(newsockfd,buf,20,0);
    printf("Buffer is %s\n",buf);

当我执行上述程序时,输出如下:

when i execute the above program, the output is as below:

客户端消息:Messgfromlient

Client Msg :Messgfromlient

我相信 buf 大小是 20,所以只有一个缓冲区被接收.在服务器端再添加一个 recv.

I believe that the buf size is 20, so only one buffer is getting received. Adding one more recv on server side.

    char buf[20],buf[20];
     ------skipped------
    recv(newsockfd,buf,20,0);
    recv(newsockfd,buf1,20,0);
    printf("Client Msg  :%s\n",buf);
    printf("Client Msg  :%s \n",buf1);

输出:第一次试用:

    Client Msg  :Messgfromlient
    Client Msg  :cli2 

第二条路线:

   Client Msg  :Messgfromlient
   Client Msg  :cli1

我们可以看到输出中存在一些矛盾,从客户端看起来所有的消息都被发送了,但是在服务器中,消息将根据 buf 大小接收,这里即使 buf1 的大小为 20,为什么 buf1 上没有收到 'cli3''cli4''cli4' 消息?.有什么具体限制吗?请澄清这一点.

As we can see that there is some contradiction in the ouputs, From client side it looks all the msgs are getting sent, but in server, msg will be received based on buf size,here eventhough buf1 has size of 20, why 'cli3''cli4''cli4' msgs are not getting received on buf1?. Is there any specific limit is there? Please clarify on this.

提前致谢,拉贾

推荐答案

TCP 是一个基于字节流的协议,它对消息一无所知.您总共发送 25 个字节,另一端的每个 recv 将读取这些字节中的一些.你可以得到 20,你可能得到 1 然后在下一次阅读中得到 19,你可能得到 5 然后 4> then 11 then 5. recv 的 size 参数是要读取的最大数量.

TCP is a byte stream based protocol, it knows nothing about messages. You send 25 bytes in total, and each recv on the other side will read some of those bytes. You can get 20, you might get 1 and then 19 in the next read, you might get 5 then 4 then 11 then 5. The size parameter to recv is the maximum number to read.

您需要循环播放,直到您自己阅读整条消息,并了解您可能会在同一条收到的消息中收到多个发送".

You need to loop until you read the whole message yourself, and also understand you might receive more than one "send" in the same received message.

这篇关于在套接字中发送多个发送/接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆