简体   繁体   English

从TCP套接字C读取

[英]Read from TCP socket C

I don't understand why function read always return -1. 我不明白为什么函数读取总是返回-1。 I want to read from socket until '\\n' appear! 我想从套接字读取直到出现“ \\ n”!

    char* msg = (char*)malloc(sizeof(char)*120);
    nleft = sizeof(msg);
    while(nleft>0){
        n = read(fdTcp, msg, nleft);
        if(n == -1){
            printf("error reading UPC\n");
            exit(1); //error
        }   
        else if (n == 0){
            printf("end of reading EOF\n");
            break; //closed by peer
        }   
        nleft-=n;
        msg += n;
    }
    nread = n-nleft;
    msg[nread] = '\0';
    printf("mensagem do CS: %s\n", msg);

Thanks in advance! 提前致谢!

char* msg = (char*)malloc(sizeof(char)*120);
nleft = sizeof(msg);

Since msg is a char* , nleft will be the number of bytes in a char* . 由于msgchar* ,因此nleft将是char*的字节数。 I don't think that's what you want. 我认为那不是你想要的。

As for answering your real question: 至于回答您的真实问题:

but I don't now how many bytes I will read, I want to ready until I reach '\\n' how can I do it? 但是我现在不读多少字节,我想准备好直到到达'\\ n'怎么办?

You have two choices. 您有两种选择。 The terrible option is to read one byte at a time until you read a newline. 糟糕的选择是一次读取一个字节,直到您读取换行符为止。 The better option is to read as much as you can and check for a newline. 更好的选择是,尽可能多地阅读并检查换行符。 If you read past the newline, great, that's just less work you'll have to do on your next pass. 如果您读过换行符,太好了,这将减少您下次通过时要做的工作。 In pseudo-code: 用伪代码:

  1. If there is not at least one newline in the buffer, skip to step 5. 如果缓冲区中至少没有换行符,请跳到步骤5。

  2. Extract the bytes up to the first newline from the buffer and process them. 从缓冲区中提取直到第一行的字节,并对其进行处理。

  3. Move any bytes past the newline to the beginning of the buffer and adjust the size of the buffer to include just those bytes. 将换行符之后的所有字节移动到缓冲区的开头,并调整缓冲区的大小以仅包括那些字节。

  4. Go to step 1. 转到步骤1。

  5. Do a blocking read and append the data to the buffer. 进行阻塞读取并将数据附加到缓冲区。

  6. Go to step 1. 转到步骤1。

I assume your socket successfuly open socket connection. 我假设您的套接字成功打开了套接字连接。 Then file discriptor is 1 that means that ready ro read data. 然后文件描述符为1,表示可随时读取数据。 You tried to read socket but you took an error with -1. 您尝试读取套接字,但使用-1出错。 Generally this error appear when the socket was closed. 通常,关闭套接字后会出现此错误。 If you took -1, socket was closed. 如果为-1,则套接字已关闭。 If took 0 that means timeout for read socket data. 如果取0,则表示读取套接字数据超时。 On the other hand if you took more than 0 this means, read how much bytes. 另一方面,如果您使用的值大于0,则意味着读取多少字节。

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

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