linux socket服务器问题,求大神详细解释下程序运行过程,代码如下~
在网上看了这个程序,服务器端可以接收多个客户端传来的信息,并且可以判断是否有新连接、连接数目、是否达到最大连接数等,小女子不才,函数的作用和代码差不多理解了,但就是想不了服务器是怎么运行的,流程是怎样的理不清思路,还希望各位大神们能抽空看一下这个程序,能详细解释下运行流程,最好再有相关代码的解释,十分感谢!!!!!
程序代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<netinet/in.h>
#include<netdb.h>
#include<arpa/inet.h>
#define PORT 1205
#define MAXNUM 3
#define MAXSIZE 1024
int fd[MAXNUM];//
int connect_num;
void showclient()
{
int i;
printf("client amount: %d\n", connect_num);
for (i = 0; i <MAXNUM; i++) {
printf("[%d]:%d ", i, fd [i]);
}
printf("\n\n");
}
int main()
{
struct sockaddr_in server;
struct sockaddr_in client;
bzero(&server,sizeof(server));
bzero(&client,sizeof(client));
char buf[MAXSIZE];
int sock_fd=socket(AF_INET,SOCK_STREAM,0);
if(sock_fd==-1)
{
print(“socket failed!\n”);
exit(-1);
}
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr=htons(“192.168.2.4”);
int bind_fd=bind(sock_fd, (struct sockaddr*)server,sizeof(server));
if(bind_fd==-1)
{
printf(“bind failed!\n”);
exit(-1);
}
int listen_fd=listen(sock_fd,MAXNUM);
if(listen_fd==-1)
{
printf(“listen failed!\n”);
exit(-1);
}
printf(“listen port:%d\n”,PORT);
}
fd_set fdsr;
int maxsock;
struct timeval tv;
connect_num= 0;
sin_size = sizeof(client_addr);
maxsock = sock_fd;//??
while (1) {
// 初始化文件描述符集合
FD_ZERO(&fdsr);
FD_SET(sock_fd, &fdsr);
// timeout setting
tv.tv_sec = 30;
tv.tv_usec = 0;
for (i = 0; i < MAXNUM; i++) {
if (fd [i] != 0) {
FD_SET(fd [i], &fdsr);
}
}
ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);
if (ret < 0) {
&