如何发送和接收数据套接字 TCP (C/C++) [英] How to send and receive data socket TCP (C/C++)

查看:30
本文介绍了如何发送和接收数据套接字 TCP (C/C++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
正确的方法是什么从 C/C++ 中的 TCP 套接字读取?

我正在尝试开发 TCP 客户端/服务器.我的问题是,当我尝试从客户端发送数据时,我会一次性发送.

I'm trying to develop a TCP client/server. My problem is, when I try to send the data from cliente I do it in one sent.

但是当我尝试接收具有特定结构的数据时,我的问题出现了,我的意思是,前 8 个字节设置日期,接下来的 10 个字节设置名称,未定义的字节数设置文本(此文本以/r/n/r/n)

But my problem appears when I try to receive the data with a specific structure, I mean, the first 8 bytes set a date, the next 10 a name, and undefined number of bytes set a text (this text ends with /r/n/r/n)

客户端发送如下:

char date[8];
char name[10];
char msg[4096];

strcpy(msg,"12/10/12"); //8 bytes
strcat(msg,"Kevin Fire"); //10 bytes
strcat(msg,"abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde

");

nbytes_sent = send(sock,(char *)msg,sizeof(msg),0);
printf("Bytes_sent: %s -> %i
",msg,nbytes_sent);

服务器尝试解析来自套接字的数据如下:

And the server try to parse the data from socket as follows:

char date[8];
char name[10];
char * text;
char buf[1024];

int i=0;
for(i=0; i < 8; i++)
    date[i] = '';
for(i=0; i < 10; i++)
    name[i] = '';

nbytes_read=recv(sclient,(char *)date,sizeof(date),0);
if(nbytes_read > 0){
    printf("Date: %s (%i)
",date,nbytes_read);
    //cout.flush();
    nbytes_read=recv(sclient,(char *)name,sizeof(name),0);
    if(nbytes_read > 0){
        printf("Name: %s (%i)
",name,nbytes_read);
        //cout.flush();
        nbytes_read=recv(sclient,(char *)buf,sizeof(buf),0);
        strcpy(text,buf);
        while(nbytes_read > 0){
            nbytes_read=recv(sclient(char*)buf,sizeof(buf),0);
            strcat(text,buf);
        }
    }
}

printf("Date: %s. Name: %s. Text: %s
",date,name,text);

推荐答案

这是一个简单的接收全部"功能:

Here's a simple "receive all" function:

int recv_all(int sockfd, void *buf, size_t len, int flags)
{
    size_t toread = len;
    char  *bufptr = (char*) buf;

    while (toread > 0)
    {
        ssize_t rsz = recv(sockfd, bufptr, toread, flags);
        if (rsz <= 0)
            return rsz;  /* Error or other end closed cnnection */

        toread -= rsz;  /* Read less next time */
        bufptr += rsz;  /* Next buffer position to read into */
    }

    return len;
}

这篇关于如何发送和接收数据套接字 TCP (C/C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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