服务器端:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <error.h>
#define PORT 8888
#define BACKLOG 5
void process_conn_server(int s);
int main()
{
int ss,sc; /*the socket descriptor of the server and the client*/
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int err; /*the return value*/
pid_t pid;
/*create a stream socket*/
ss = socket(AF_INET,SOCK_STREAM,0);
/*check the return value*/
if(ss < 0)
{
perror("socket error:");
return -1;
}
/*set the struct of the address of the server*/
bzero(&server_addr,sizeof(server_addr)); /*clean*/
server_addr.sin_family = AF_INET;
server_addr.port = htons(PORT);
server_addr.sin_addr.s_addr = htol(INADDR_ANY);
/*bind the socket to the addrs*/
err = bind(ss,(struct sockaddr*)&server_addr,
sizeof(server_addr));
if(err < 0)/*check the return value*/
{
perror("bind error:");
return -1;
}
/*set listen*/
err = listen(ss,BACKLOG);
if(err < 0)
{
perror("listen error:");
return -1;
}
for(;;)
{
int addrlen = sizeof(struct sockaddr);
/*accept a connection and create a new socket descriptor*/
sc = accept(ss,(struct sockaddr*)&client_addr,&addrlen);
if(sc <0)
{
continue;
}
/*create a new process to deal with the new connect*/
pid = fork();
if(pid == 0) /*this is the child process*/
{
close(ss);
process_conn_server(sc); /*the process function*/
}
else /*this is the parent process*/
{
close(sc);
}
}
/*the defination of the process function*/
void process_conn_server(int s)
{
ssize_t size = 0;
char buffer[1024];
for(;;)
{
size = read(s,buffer,1024);
if(size == 0)
{
return ;
}
sprintf(buffer,"%d bytes altogether/n",size);
write(s,buffer,strlen(buffer)+1);/*send to the client*/
}
}
}