Код: Выделить всё
g++ socket.cpp
./a.out
Код: Выделить всё
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <signal.h>
#include <string.h>
#include <string>
using std::string;
class tcpdaemon
{
protected:
void daemonize();
void mainloop();
void operate(int fd);
static void signalhandler(int signum);
public:
void exec();
};
void tcpdaemon::signalhandler(int signum)
{
waitpid(0, 0, WNOHANG);
}
void tcpdaemon::daemonize()
{
struct sigaction sa;
printf("Welcome to Playback Price Server. Server start OK!\n");
int pid = fork();
switch(pid)
{
case 0:
setsid();
chdir("/");
close(0);
close(1);
close(2);
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &signalhandler;
sigaction(SIGCHLD, &sa, 0);
exit(0);
case -1:
printf("Fork error...\n");
break;
default:
printf("OK. PID=%d\n", pid);
break;
}
}
void tcpdaemon::mainloop()
{
int sockfd, fd;
struct sockaddr_in sa;
socklen_t n;
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(sockfd != -1)
{
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_ANY);
sa.sin_port = htons(21867);
if(bind(sockfd, (struct sockaddr *)&sa, sizeof sa) != 1)
{
while(1)
{
if(!listen(sockfd, 50))
{
n = sizeof sa;
if((fd = accept(sockfd, (struct sockaddr *)&sa, &n)) != -1)
{
printf("Connection from %s", inet_ntoa(sa.sin_addr));
if(!fork)
{
operate(fd);
}
}
}
}
}
}
}
void tcpdaemon::operate(int fd)
{
char c;
bool finished;
string cmd, answer;
finished = false;
write(fd, answer.c_str(), answer.size());
while(!finished)
{
cmd = answer = "";
while(!finished)
finished = read(fd, &c, 1) != 1;
if(c == '\n')
break;
else if(c != '\r')
cmd += c;
if(!finished && !cmd.empty())
{
if(cmd == "info")
answer = "Welcome to PlayBack Price Server...";
else if(cmd == "quit")
{
shutdown(fd, 2);
close(fd);
finished = true;
}
}
}
if(!finished && !answer.empty())
{
answer += "\n";
write(fd, answer.c_str(), answer.size());
}
exit(0);
}
void tcpdaemon::exec()
{
daemonize();
}
int main()
{
tcpdaemon daemon;
daemon.exec();
return 0;
};