HTTPServer.C
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039 #include <sys/socket.h>
00040 #include <netinet/in.h>
00041 #include <stdio.h>
00042 #include <unistd.h>
00043 #include <stdlib.h>
00044 #include <string.h>
00045 #include <pthread.h>
00046 #include <signal.h>
00047
00048 #include "Devices/HTTPServer.H"
00049
00050 #include "Component/OptionManager.H"
00051 #include "Component/ModelOptionDef.H"
00052 #include "Devices/DeviceOpts.H"
00053 #include "Util/log.H"
00054 #include "rutz/unixcall.h"
00055
00056 extern const ModelOptionCateg MOC_HTTP;
00057
00058 const ModelOptionCateg MOC_HTTP = {
00059 MOC_SORTPRI_2, "HttpServer-Related Options" };
00060
00061 static const ModelOptionDef OPT_HttpServerPort =
00062 { MODOPT_ARG(uint), "ServerPort", &MOC_HTTP, OPTEXP_CORE,
00063 "Port number of the server to use ",
00064 "HttpServer-port", '\0', "<portnum>", "80" };
00065
00066
00067
00068 HttpServer::HttpServer(OptionManager& mgr,
00069 const std::string& descrName,
00070 const std::string& tagName) :
00071 ModelComponent(mgr, descrName, tagName),
00072 itsPort(&OPT_HttpServerPort, this),
00073 itsSocket(-1)
00074 {
00075
00076 }
00077
00078
00079 HttpServer::~HttpServer(void)
00080 {
00081 LINFO("Clossing connections");
00082 close(itsSocket);
00083
00084 }
00085
00086
00087
00088 void HttpServer::start1()
00089 {
00090
00091
00092 struct sockaddr_in servaddr;
00093
00094
00095 signal(SIGPIPE, SIG_IGN);
00096
00097 itsSocket=socket(AF_INET,SOCK_STREAM,0);
00098 if (itsSocket < 0)
00099 LFATAL("Can not create socket\n");
00100
00101 bzero(&servaddr,sizeof(servaddr));
00102 servaddr.sin_family = AF_INET;
00103 servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
00104 servaddr.sin_port=htons(itsPort.getVal());
00105
00106
00107 long arg;
00108 if( (arg = fcntl(itsSocket, F_GETFL, NULL)) < 0)
00109 LFATAL("Error fcntl(..., F_GETFL)\n");
00110 arg |= O_NONBLOCK;
00111
00112 if( fcntl(itsSocket, F_SETFL, arg) < 0)
00113 LFATAL("Error fcntl(..., F_SETFL)\n");
00114
00115
00116 if (bind(itsSocket,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0)
00117 LFATAL("Can not bind to port: %i\n", itsPort.getVal());
00118
00119 if (listen(itsSocket,1024) < 0)
00120 LFATAL("Can not listen to port\n");
00121 }
00122
00123
00124 void HttpServer::stop2()
00125 {
00126 close(itsSocket);
00127 }
00128
00129 int HttpServer::acceptConn()
00130 {
00131 struct sockaddr_in cliaddr;
00132 socklen_t clilen=sizeof(cliaddr);
00133
00134 return accept(itsSocket,(struct sockaddr *)&cliaddr,&clilen);
00135 }
00136
00137 int HttpServer::writeData(int clientFd, std::string& msg)
00138 {
00139 return write(clientFd, msg.c_str(), msg.size());
00140 }
00141
00142
00143
00144
00145
00146
00147