#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <signal.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main(int argc, char * argv[])
{
int sockfd, res;
int clientfd;
struct sockaddr_in dest;
char buffer[3] = "% ", buffer1[65535];
char welcome[500] = "****************************************\n** Welcome to the information server. **\n****************************************\n% ";
pid_t child;
socklen_t clilent;
setvbuf(stdout, NULL, _IONBF, 0);
bzero(&dest, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(5432);
dest.sin_addr.s_addr = INADDR_ANY;
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
perror("Socket Error");
exit(-1);
}
if(bind(sockfd, (struct sockaddr*)&dest, sizeof(dest)) < 0)
{
perror("Bind Error");
close(sockfd);
exit(-1);
}
if(listen(sockfd, 1) < 0)
{
perror("Listen Error");
close(sockfd);
exit(-1);
}
while(1)
{
struct sockaddr_in client_addr;
int addrlen = sizeof(client_addr);
/*Accept*/
if(clientfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&addrlen) < 0)
{
perror("Accpet Error");
close(sockfd);
exit(-1);
}
/*Fork process*/
if(child = fork() < 0)
{
perror("Fork Error");
close(sockfd);
exit(-1);
}
else if(child == 0)
{
int my_client = clientfd;
close(sockfd);
send(my_client, welcome, sizeof(welcome), 0);
while ((res = recv(my_client, buffer1, sizeof(buffer1), 0)) > 0)
{
string command(buffer1);
cout << "receive from client:" << command << ", " << res << " bytes\n";
memset(buffer1, '\0', sizeof(buffer1));
}
}
close(clientfd);
}
return 0;
}