套接字设置没有错误,但没有连接

时间:2017-01-16 15:06:21

标签: c++ tcp

我正在尝试学习如何通过2台Linux机器使用TCP / IP,这两台机器都具有正常的互联网连接。我尝试设置服务器和客户端,但我没有得到连接,尽管在安装过程中没有出现任何错误。

服务器代码:

return( <ChildComponent {...this.state} /> );

我希望输出是打印我的IP地址和端口的消息,然后是等待消息,然后是宣布连接的消息,然后是宣布来自客户端的请求的消息,以及传入的文本。

客户代码:

int serverSocketFd,clientSocketFd,clientLength,numberOfBytes;
static struct sockaddr_in server_address, clint address;
char buf[256];

serverSocketFd = socket(AF_INET,SOCK_STREAM,0);
if(serverSocketFd<0){error("socket() call Failed");}

//Clears the allocated space of the sockaddr_in struct before configuration
bzero((char *)&server_address, sizeof(server_address));

server_address.sin_family = AF_INET;
//inet_aton should take an IP address in string format and convert it to the proper format for the struct. Returns nonzero for error
if(!inet_aton("XXX.XXX.XXX.XXX",&(server_address.sin_addr))){error("inet_aton() Failed");}

//Picked a random port number for this test
server_address.sin_port = htons(34567);

//Quick check that I have the expected settings
inet_ntop(AF_INET,&server_address.sin_addr,buf,255);
printf("Listening on %s:%d\n",buf,server_address.sin_port);

if(bind(serverSocketFd,(struct sockaddr *)&server_address,sizeof(server_address)) <0){error("bind() call Failed");}

//At this point, Socket should be prepped to start listening, and waits here until another program makes contact
printf("Waiting on client...\n");
listen(serverSocketFd,5);

//If a client program makes a connection, the 'clinetSocketFd' represents it
clientLength = sizeof(client_address);
clientSocketFd = accept(serverSocektFd, (struct sockaddr *)&clinet_address, (socklen_t *)&clientLength);
if(clientSocketFd < 0){error("accept() call returned invalid");}

printf("CONNECTION ACCEPTED\n");

//Now that a connection is established, wait for a request from client
bzero(buf,256);
numberOfBytes = read(clientSocketFd,buf,255);
if(numberOfBytes<0){error("read() call Failed");}

printf("MESSAGE RECEIVED: %s\n",buf);

numberOfBytes = write(clientSocketFd,"ACKNOWLEDGED",strlen("ACKNOWLEDGED"));
return numberOfBytes;

我希望输出大致相同,打印目标IP和端口,确认消息,然后是收到的确认。

我最终在两台机器上看到的都是听/连接阶段。

我看到&#34;正在/正在连接到XXX.XXX.XXX.XXX:34567" ;,它与运行服务器代码的计算机上的IP地址匹配。然后它超时了。 errno设置为ECONNREFUSED。

永远不会建立连接,但在此之前没有出现错误,因此在配置套接字时似乎没有出现任何问题。

有人可以用这段代码解释问题是什么吗?

0 个答案:

没有答案