UNIX TCP / IP Read: Transport endpoint not connected. Read: Transport endpoint is not connected.

I am trying to use the following program to display the received message feed 8888

. I have compiled the following code without any errors or warnings.

Once launched, I use broswer to open 127.0.0.1:8888

Then the console showed:

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

      

I am debugging it but I cannot find the reason.

platform

Linux Kernel 3.x Ubuntu 64bit

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 find any bad habits in my code, please let me know.

+3


source to share


1 answer


You are trying to read the wrong socket. accept()

returns a new socket, and it is this new socket that should read data and write data.

Your code should do something more:



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
}

      

+9


source







All Articles