|
发表于 2004-5-16 10:02:11
|
显示全部楼层
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<netdb.h>
#include<unistd.h>
#define THEPORT 5000
#define BACKLOG 10
#define HEADS 16
void str_send(int sock_fd)
{
int length;
int num[HEADS];
int i;
for(i=0;i<HEADS;i++)
num = i;
length = sizeof(num[0]) * HEADS;
while((send(sock_fd,&length,sizeof(length),0) > 0)&&(send(sock_fd,num,length,0) > 0));
}
main()
{
int sock_fd,new_fd;
struct sockaddr_in this_addr;
struct sockaddr_in that_addr;
int sin_size;
int child;
if ((sock_fd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
this_addr.sin_family=AF_INET;
this_addr.sin_port=htons(THEPORT);
this_addr.sin_addr.s_addr=INADDR_ANY;
bzero(&(this_addr.sin_zero),8);
if (bind(sock_fd,(struct sockaddr *) &this_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
while(1)
{
if (listen(sock_fd,BACKLOG)==-1)
{
perror("listen");
exit(1);
}
sin_size=sizeof(struct sockaddr_in);
if ((new_fd=accept(sock_fd,(struct sockaddr *) &that_addr,&sin_size))==-1)
{
perror("accept");
exit(1);
}
printf("Server:Got connection from %s\n",inet_ntoa(that_addr.sin_addr));
child = fork();
if(child == 0)
{
/*创建子进程*/
str_send(new_fd);
close(new_fd);
_exit(0);
}
else
{
/*父进程*/
printf("Server: fork() OK! child = %d\n",inet_ntoa(that_addr.sin_addr), child);
}
}
close(sock_fd);
} |
|