我是Linux上用C编程的新手,我尝试创建一个服务器。我打开了接受方法。客户试图连接但没有任何反应!我不知道为什么。想帮帮我吗?
服务器端:
int main(int argc, char *argv[])
{
int len,err,port;
if(argc != 2) {
exit(1);
}
initSem();
port = atoi(argv[1]);
initSocket(port);
printf("server fd: %d.\n", serverFd);
len = sizeof(struct sockaddr_in);
printf("len: %d\n",len);
clientsFd[counterThread] = accept(serverFd,
(struct sockaddr*)&clientsAddress[counterThread],
(socklen_t*)&len);
printf("new client:: %d", clientsFd[counterThread]);
if(clientsFd[counterThread] == -1) {
perror("can't connect to new client.");
exit(1);
}
return 0;
}
void initSocket(int port)
{
erverFd = socket(AF_INET, SOCK_STREAM, 0);
serverAdrees rees.sin_addr.s_addr = INADDR_ANY;
serverAdrees.sin_port = htons(port);
bind(serverFd, (struct sockaddr*)&serverAdrees, (socklen_t)sizeof(struct sockaddr_in));
listen(serverFd, MAX_CLIENTS);
}
客户端:
int main(int argc, char *argv[])
{
int err,len,port;
struct sockaddr_in serverAddr;
char massageBuf[MAX_MASSAGE];
pthread_t readThread;
if(argc != 3) {
perror("no arguments..\n");
return 1;
}
if((serverFd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("\n Error : Could not create socket \n");
return 1;
}
printf("server fd: %d.\n", serverFd);
serverAddr.sin_family = AF_INET;
port = atoi(argv[2]);
serverAddr.sin_port = htons(port);
printf("addr: %s .\n", argv[1]);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
printf("before connect\n");
if(connect(serverFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
{
perror("\n Error : Connect Failed \n");
return 1;
}
printf("after connect \n");
while (1) {
scanf("%s", massageBuf);
printf("%s \n", massageBuf);
if(-1 == write(serverFd, massageBuf, strlen(massageBuf))) {
perror("\n Error : write to server Failed \n");
return 1;
}
if(!strcmp(massageBuf,"close")) {
exit(1);
return 0;
答案 0 :(得分:1)
您的客户端尝试连接到INADDR_ANY,这是对的。将connect()调用您作为命令行参数提供的地址。
除此之外,很难说,因为代码不是很SSCCE。正如评论所示,请尝试清理它。删除initSem();
之类的调用(或显示其代码)和clientsFd[counterThread]
编辑删除了有关accept()
的建议,我的错误。