socket.cpp
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
00029 #include "socket.h"
00030
00034 Socket::Socket()
00035 {
00036 this->mySock = -1 ;
00037 this->state = false;
00038 }
00039
00043 Socket::~Socket()
00044 {
00045 this->closeSock();
00046 }
00047
00056 bool Socket::connectSock(int port, string serverName, string dedicatedIP)
00057 {
00058 struct sockaddr_in sockname;
00059 struct hostent *hostname;
00060 hostname = gethostbyname (serverName.c_str());
00061 if ( hostname == NULL )
00062 return false;
00063 if (hostname->h_addrtype != AF_INET)
00064 return false;
00065 if ((this->mySock=socket(AF_INET, SOCK_STREAM, 0)) <0)
00066 return false;
00067 memset ((char *) &sockname, 0, sizeof (struct sockaddr_in));
00068 memcpy ((char *) &sockname.sin_addr, (char*)hostname->h_addr, hostname->h_length);
00069 sockname.sin_family = AF_INET;
00070 sockname.sin_port = htons ((u_short)port);
00071 if ( dedicatedIP != "" )
00072 {
00073 struct sockaddr_in msim;
00074 unsigned long opt = 1;
00075 msim.sin_addr.s_addr = inet_addr (dedicatedIP.c_str());
00076 msim.sin_family = AF_INET;
00077 msim.sin_port = htons (0);
00078 setsockopt (this->mySock, SOL_SOCKET, SO_REUSEADDR, (char *) &opt,sizeof (opt));
00079 if (bind (this->mySock, (struct sockaddr *) &msim, sizeof (msim)) < 0)
00080 {
00081 cout << "ERROR : unable to bind socket"<<endl;
00082 exit(-1);
00083 }
00084 }
00085 if ((connect (this->mySock, (struct sockaddr *) &sockname, sizeof (struct sockaddr))) < 0)
00086 return false;
00087 this->state = true;
00088 return true;
00089 }
00090
00095 bool Socket::closeSock()
00096 {
00097 if ( close(this->mySock) < 0 ) {
00098 return false ;
00099 }
00100 else {
00101 this->state = false;
00102 return true ;
00103 }
00104 }
00105
00110 bool Socket::getState()
00111 {
00112 return this->state;
00113 }
00114
00119 string Socket::receive()
00120 {
00121 const unsigned int MAXDATAS = 1024;
00122 char buffer[MAXDATAS];
00123 int numbytes ;
00124 struct timeval tv;
00125 fd_set readfds;
00126 tv.tv_sec = 0;
00127 tv.tv_usec = 050000;
00128 FD_ZERO(&readfds);
00129 FD_SET(this->mySock, &readfds);
00130 if (select(this->mySock+1, &readfds, NULL, NULL, &tv) >=0 ) {
00131 if (FD_ISSET(this->mySock, &readfds)) {
00132 if((numbytes=recv(this->mySock,buffer,MAXDATAS, 0))<=0) {
00133 this->closeSock();
00134 return "";
00135 }
00136 else {
00137 return ((string)buffer).substr(0,numbytes) ;
00138 }
00139 }
00140 else {
00141 return "";
00142 }
00143 }
00144 this->state = false;
00145 return "";
00146 }
00147
00153 bool Socket::sendStr(string strData)
00154 {
00155 if( send(this->mySock, strData.c_str(), strData.length(),MSG_NOSIGNAL) < 0 ) {
00156 return false ;
00157 }
00158 else {
00159 return true ;
00160 }
00161 }