im试图在Linux(Ubuntu)上用c ++编写一个简单的服务器/客户端程序。但是现在我的服务器代码出现了问题。 我可以编译代码,但是当我运行它时,它每次都会在bind函数中卡住。但是我没有收到错误信息。它甚至运行了几分钟,我没有收到任何反馈。你们知道为什么它不起作用吗?
感谢您的帮助。
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<iostream>
int main()
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
std::cout << "Creating socket..\n";
sockfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, 0, sizeof(serv_addr));
portno = atoi("5001");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
std::cout << "Binding socket..\n";
int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
std::cout << "setsockopt(SO_REUSEADDR) failed\n";
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
std::cout << "ERROR on binding\n";
std::cout << "Listening..";
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
std::cout << "ERROR on accept\n";
bzero(buffer,256);
n = read(newsockfd,buffer,255);
n = write(newsockfd,"I got your message",18);
close(newsockfd);
close(sockfd);
return 0;
}
我使用以下命令进行编译:c ++ server.cpp -o server
要运行它,我使用:./server
答案 0 :(得分:2)
将std::cout << "Listening..";
替换为std::cout << "Listening.." << std:flush;
,然后阅读How does std::flush work?,了解您的未来项目
基本上,您的服务器已经在侦听新的连接,但是您缺少控制台上的“ Listening ..”输出,不是吗?