简体   繁体   English

UNIX TCP/IP:读取:传输端点未连接读取:传输端点未连接

[英]UNIX TCP/IP :read: Transport endpoint is not connected read: Transport endpoint is not connected

I'm trying to use the following program to show the message recived form port 8888 .我正在尝试使用以下程序来显示从端口8888收到的消息。 I compiled the following code without any error and warning.我编译了以下代码,没有任何错误和警告。

After I run it, I use a broswer to open 127.0.0.1:8888运行后,我用broswer打开127.0.0.1:8888

Then, the console showed:然后,控制台显示:

read: Transport endpoint is not connected
read: Transport endpoint is not connected

I debug it, but I can't find the reason.我调试了一下,找不到原因。

platform平台

Linux kernel 3.x Ubuntu 64bit Linux kernel 3.x Ubuntu 64 位

code代码

#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <netinet/in.h>
//#include <errno.h>

int main(int argc, char *argv[])
{
    int sock;
    char buf[BUFSIZ+1];

    buf[BUFSIZ] = '\0';
    uint16_t port = (uint16_t)atoi("8888");
    struct sockaddr_in ser;
    memset(&ser, 0, sizeof(ser));
    ser.sin_port = htons(port);
    ser.sin_addr.s_addr = htonl(INADDR_ANY);
    ser.sin_family = AF_INET;

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sock < 0)
    {
        perror("socket");
        return -7;
    }

    /*Bind*/
    if (bind(sock, (struct sockaddr *)&ser, sizeof(ser)) < 0)
        return -2;

    /*listen*/
    if (listen(sock, 5) < 0)
        return -3;

    /*Accpet*/
    struct sockaddr_in cliAddr;
    socklen_t cliLen = sizeof(cliAddr);
    if (accept(sock, (struct sockaddr*)&cliAddr, &cliLen) < 0)
    {
        perror("accept");
        exit(1);
    }
    int read_len = 0;
    int i = 0;

    /*read and print*/
    while(1)
    {
        read_len = read(sock, buf, BUFSIZ);
        if(read_len < 0)
        {
            perror("read");
            break;
        }
        else
        {
            /*print buf*/
            while(i++ < read_len)
                putchar(buf[i-1]);
            putchar('\n');
        }
        if(read_len != BUFSIZ)
            break;
    }
    return 0;
}

If you found any bad habits in my code, please tell me.如果您在我的代码中发现任何不良习惯,请告诉我。

You're trying to read the wrong socket.您正在尝试读取错误的套接字。 accept() returns a new socket and it is that new socket you should be reading the data from and writing data to. accept()返回一个新的套接字,它就是您应该从中读取数据和向其写入数据的新套接字。

Your code should do something more like this:您的代码应该更像这样:

int readSocket = accept(sock ...);
if (readSocket == -1)
{
    // error
}
else
{
    // set up stuff and while loop
    read_len = read(readSocket....); // << Note which socket is being read

    // other stuff
}

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

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