00001 #include "Connection.h"
00002
00003 Connection::Connection(int port){
00004 this->port = port;
00005 isConnected = false;
00006
00007 WSAData wsaData;
00008 if(WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
00009 throw "Error at WSAStartup.";
00010
00011 tcp = socket(AF_INET, SOCK_STREAM, 0);
00012 if(tcp == INVALID_SOCKET){
00013 WSACleanup();
00014 throw "Error creating socket.";
00015 }
00016
00017 int on = 1;
00018 setsockopt(tcp, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
00019 isOpen = false;
00020 }
00021
00022
00023 Connection::Connection(SOCKET s){
00024 tcp = s;
00025 this->port = 0;
00026
00027 isConnected = false;
00028 isOpen = true;
00029
00030 }
00031
00032
00033 int Connection::connectByIp(char *addr){
00034 struct hostent *hostentry;
00035 sockaddr_in serverInfo;
00036
00037 hostentry = gethostbyname(addr);
00038 if(!hostentry)
00039 return(-1);
00040 serverInfo.sin_family = AF_INET;
00041 serverInfo.sin_port = htons(port);
00042 serverInfo.sin_addr = *((struct in_addr *)hostentry->h_addr);
00043
00044 if(connect(tcp, (struct sockaddr *)&serverInfo, sizeof(serverInfo)) == SOCKET_ERROR){
00045 WSACleanup();
00046 return(-1);
00047 }
00048 isConnected = true;
00049 return(0);
00050 }
00051
00052
00053 Connection *Connection::waitForConnection(){
00054 SOCKET client;
00055 Connection *newConn;
00056
00057 if(!isOpen){
00058 sin.sin_family = AF_INET;
00059 sin.sin_port = htons(port);
00060 sin.sin_addr.s_addr = INADDR_ANY;
00061
00062 if(bind(tcp, (struct sockaddr *)&sin, sizeof(sin)) == SOCKET_ERROR){
00063 WSACleanup();
00064 LOG_ERROR(("ERROR BIND"));
00065 return(NULL);
00066 }
00067
00068 if(listen(tcp, 1) == SOCKET_ERROR){
00069 LOG_ERROR(("ERROR LISTEN"));
00070 WSACleanup();
00071 closesocket(tcp);
00072 return(NULL);
00073 }
00074 }
00075 client = accept(tcp, NULL, NULL);
00076 if(tcp == SOCKET_ERROR){
00077 LOG_ERROR(("ERROR ACCEPT"));
00078 WSACleanup();
00079 closesocket(tcp);
00080 return(NULL);
00081 }
00082 newConn = new Connection(tcp);
00083 tcp = client;
00084 isConnected = true;
00085 return(newConn);
00086 }
00087
00088
00089
00090
00091
00092 int Connection::disconnect(){
00093 closesocket(tcp);
00094 return(0);
00095 }
00096
00097
00098
00099 int Connection::recieveData(char *buf, int size, int flag){
00100 int br;
00101 if(!isConnected)
00102 return(-1);
00103 if((br = recv(tcp, buf, size, flag)) == SOCKET_ERROR){
00104 closesocket(tcp);
00105 return(-1);
00106 }
00107 return(br);
00108 }
00109
00110
00111 int Connection::sendData(char *buf, int size){
00112 int bs;
00113 if(!isConnected)
00114 return(-1);
00115 if((bs = send(tcp, buf, size, 0)) == SOCKET_ERROR){
00116 closesocket(tcp);
00117 return(-1);
00118 }
00119 return(bs);
00120 }
00121
00122
00123 int Connection::getLastError(){
00124 return(WSAGetLastError());
00125 }
00126
00127
00128 int Connection::getPort(){
00129 return(this->port);
00130 }