Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008 #include <iostream>
00009 #include <cstdlib>
00010 #include <cstring>
00011 #include <sys/socket.h>
00012 #include <netinet/in.h>
00013 #include <boost/thread.hpp>
00014 #include <boost/bind.hpp>
00015 #include <arpa/inet.h>
00016 #include <cstdio>
00017 #include "server.h"
00018 #include "worker.h"
00019 using namespace std;
00020
00021
00022 Server::Server(int port)
00023 {
00024 portno = port;
00025 net_bufferSize = 1024;
00026 }
00027
00037 void Server::start()
00038 {
00039 listenFd = socket( AF_INET, SOCK_STREAM,0 );
00040 if (listenFd < 0) {
00041 error("Error opening socket");
00042 }
00043 sockaddr_in serverAddr;
00044 sockaddr &serverAddrCast = (sockaddr &) serverAddr;
00045
00046
00047 socklen_t addr_size;
00048 struct sockaddr_storage client_addr;
00049
00050 memset(&serverAddr,0,sizeof( serverAddr) );
00051 serverAddr.sin_family = AF_INET;
00052 serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
00053 serverAddr.sin_port = htons(portno);
00054
00055 if (( bind(listenFd, &serverAddrCast, sizeof( serverAddr )) < 0 )) {
00056 error("ERROR on binding");
00057 }
00058
00059 listen(listenFd,5);
00060 running = true;
00061
00062 while(running)
00063 {
00064 cout << "Waiting for connection" << endl;
00065 csock = (int*)malloc(sizeof( int ));
00066
00067 *csock = accept(listenFd, (struct sockaddr*)&client_addr, &addr_size);
00068 if (csock < 0)
00069 {
00070 cout << "Connection failed" << endl;
00071 free(csock);
00072 continue;
00073 }
00074
00075
00076
00077
00078
00079
00080 cout << "Connection accepted" << endl;
00081 boost::thread thread(&Server::newJob, this, csock);
00082 }
00083 }
00090 void Server::stop()
00091 {
00092 cout << "Server has been asked to stop!" << endl;
00093 cout << "Closing socket...";
00094 running = false;
00095 shutdown(listenFd, 2);
00096 close(listenFd);
00097 cout << "done!" << endl;
00098 }
00105 void Server::killConnection()
00106 {
00107 cout << "Server closing" << endl;
00108 shutdown(listenFd,2);
00109 close(listenFd);
00110 }
00118 void Server::error(const char *msg)
00119 {
00120 cerr << msg << endl;
00121 exit(1);
00122 }
00130 void Server::newJob(int* fd)
00131 {
00132 Worker wt( (void*) fd);
00133 wt.comm();
00134 }