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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10044872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:38:45  来源:igfitidea点击:

UNIX TCP/IP :read: Transport endpoint is not connected read: Transport endpoint is not connected

clinuxsocketstcp

提问by thlgood

I'm trying to use the following program to show the message recived form port 8888. I compiled the following code without any error and warning.

我正在尝试使用以下程序来显示收到的消息 port 8888。我编译了以下代码,没有任何错误和警告。

After I run it, I use a broswer to open 127.0.0.1:8888

运行后,我用浏览器打开 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 内核 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] = '
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
}
'; 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.

如果您在我的代码中发现任何不良习惯,请告诉我。

回答by JeremyP

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:

您的代码应该更像这样:

##代码##