我正在尝试用c编写客户端/服务器程序。 我连接被拒绝了。我无法弄清问题是什么 任何人都可以帮助我。
这是服务器
// include directories
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "unistd.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "netinet/in.h"
#include "strings.h"
#include "arpa/inet.h"
#include "math.h"
#define PORTNUM 1300
#define LISTENQ 10
#define BUFFER 1024
int main( int argc, char *argv[] )
{
int i, maxi, maxfd, listenfd, connfd, sockfd, flag, previousfd;
int nready, client[FD_SETSIZE];
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
fd_set rset, allset;
ssize_t n;
struct frame fpart, bufferedPart1,bufferedPart2 ;
char recvline[BUFFER], sendline[BUFFER];
/* First call to socket() function */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Socket Error");
exit(-1);
}
printf("I ma here");
/* Initialize socket structure */
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5000);
servaddr.sin_addr.s_addr = INADDR_ANY;
/* Now bind the host address using bind() call.*/
if((bind(sockfd,(struct sockaddr *)&servaddr, sizeof(struct sockaddr_in)))== -1)
{
perror("Bind Error");
exit(-1);
}
printf("I ma here");
/* Now start listening for the clients */
listen(listenfd, LISTENQ);
printf("I ma here");
flag = 0;
maxfd = listenfd; /* initialize */
maxi = -1; /* index into client[] array */
for (i = 0; i < FD_SETSIZE; i++)
client[i] = -1; /* -1 indicates available entry */
FD_ZERO(&allset);
FD_SET(listenfd, &allset);
for ( ; ; ) {
rset = allset; /* structure assignment */
nready = select(maxfd + 1, &rset, NULL, NULL, NULL);
if (FD_ISSET(listenfd, &rset)) {
/* new client connection */
clilen = sizeof(cliaddr);
printf("I ma here");
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
for (i = 0; i < FD_SETSIZE; i++)
if (client[i] < 0) {
client[i] = connfd; /* save descriptor */
break;
}
if (i == FD_SETSIZE)
perror("too many clients");
FD_SET(connfd, &allset); /* add new descriptor to set */
if (connfd > maxfd)
maxfd = connfd; /* for select */
if (i > maxi)
maxi = i; /* max index in client[] array */
if (--nready <= 0)
continue; /* no more readable descriptors */
}
for (i = 0; i <= maxi; i++) {
/* check all clients for data */
if ( (sockfd = client[i]) < 0)
continue;
if (FD_ISSET(sockfd, &rset)) {
if ( (n = read(sockfd, recvline, sizeof(recvline))) == 0) {
/* connection closed by client */
close(sockfd);
FD_CLR(sockfd, &allset);
client[i] = -1;
} }
if (--nready <= 0)
break; /* no more readable descriptors */
}
}
}
}
服务器应该能够收听多个客户端。所以我用了select。
答案 0 :(得分:0)
根据man 2 listen
,第一个参数应该是应该为连接监听的套接字的文件描述符。
在服务器的代码中,listenfd
未初始化。实际上listen(2)
所需要的是具有文件描述符sockfd
的套接字。
在致电listenfd
之前将sockfd
初始化为listen(2)
,或在服务器端将listenfd
替换为sockfd
,它应该有效。
此外,请参阅this question,了解何时在"..."
声明中使用<...>
和#include
。