Go to the documentation of this file.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 #include "DcSocketServer.h"
00027 
00028 #define DEFAULT_PORT    80
00029 
00030 int CdcSocketServer::nObjCounter = 0;
00031 
00032 CdcSocketServer* CdcSocketServer::GetSocketServer (int port) throw (CdcException)
00033 {
00034     
00035     if ( nObjCounter > 0 )
00036         throw CdcException ("More than one server socket.");
00037     nObjCounter++;
00038 
00039     SOCKADDR_IN local;
00040     SOCKET servsock;
00041 
00042     
00043     local.sin_family = AF_INET;
00044     local.sin_addr.s_addr = INADDR_ANY;
00045     local.sin_port = htons (port);  
00046 
00047     
00048     servsock = socket (AF_INET, SOCK_STREAM, 0);    
00049     if (servsock == INVALID_SOCKET)
00050         throw CdcExceptionSocket (WSAGetLastError());
00051 
00052     
00053     if ( bind (servsock,(struct sockaddr*)&local, sizeof(local) )
00054         == SOCKET_ERROR)
00055         throw CdcExceptionSocket (WSAGetLastError());
00056 
00057     
00058     CdcSocketServer* psocsrv = new CdcSocketServer;
00059     psocsrv->Init (servsock);   
00060 
00061     
00062     return psocsrv;
00063 }
00064 
00065 
00066 CdcSocketServer* CdcSocketServer::GetSocketServer () throw (CdcException)
00067 {
00068     return GetSocketServer (DEFAULT_PORT);
00069 }
00070 
00071 
00072 CdcSocket* CdcSocketServer::Listen () throw (CdcException)
00073 {
00074     SOCKADDR_IN from;
00075     int fromlen = sizeof(from);
00076 
00077     
00078     int ret = listen (oSocket, SOMAXCONN);
00079 
00080     
00081     if (ret  == SOCKET_ERROR)
00082         throw CdcExceptionSocket (WSAGetLastError());
00083 
00084     
00085     SOCKET msgsock = accept (oSocket, (struct sockaddr*)&from, &fromlen);
00086 
00087     
00088     CdcSocket* psock = CdcSocket::GetNewSocket (msgsock, from);
00089 
00090     
00091     return psock;
00092 }
00093 
00094 
00095 CdcSocket* CdcSocketServer::ListenNonBlock (int wait) throw (CdcException)
00096 {
00097     FD_SET set;
00098     FD_ZERO (&set);
00099     FD_SET (oSocket, &set);
00100     struct timeval swait = {0, wait * 1000};
00101     int ret;
00102     SOCKADDR_IN from;
00103     int fromlen = sizeof(from);
00104 
00105     
00106     ret = listen (oSocket, 0);
00107     if (ret == SOCKET_ERROR)
00108         throw CdcExceptionSocket (WSAGetLastError());
00109     
00110     ret = select (1, &set, NULL, NULL, &swait);
00111     
00112     if (ret == 0) return NULL;
00113     
00114     if (ret  == SOCKET_ERROR)
00115         throw CdcExceptionSocket (WSAGetLastError());
00116     
00117     SOCKET msgsock = accept (oSocket, (struct sockaddr*)&from, &fromlen);
00118     
00119     CdcSocket* psock = CdcSocket::GetNewSocket (msgsock, from);
00120     
00121     return psock;
00122 }