Main Page | Class List | File List | Class Members | File Members

socket.cpp

Go to the documentation of this file.
00001 00009 #include "socket.h" 00010 00011 Socket::Socket() {} 00012 00013 Socket::~Socket() {} 00014 00015 00016 void Socket::Connect(const string& ip, int port) { 00017 #ifdef WIN32 00018 struct WSAData WSA; 00019 #endif 00020 unsigned long _true=1; 00021 unsigned long _false=0; 00022 int result; 00023 00024 //==== set address ======= 00025 // clear Ser4vAddress structure 00026 bzero(&ServAddress, sizeof(ServAddress)); 00027 // fill the ServAddress structure with IP... 00028 ServAddress.sin_addr.s_addr = inet_addr(ip.c_str()); 00029 // ... port 00030 ServAddress.sin_port = htons(port); 00031 // ... and family 00032 ServAddress.sin_family = AF_INET; 00033 00034 #ifdef WIN32 00035 WSAStartup(17, &WSA); 00036 #endif 00037 //==== create socket ====== 00038 // create an internet-stream socket == TCP socket 00039 socket_fd = socket(AF_INET, SOCK_STREAM, 0); 00040 if (socket_fd < 0) {/*error*/ 00041 throw "Socket::Connect - Socket creation failed (socket)"; 00042 }; 00043 00044 //set non-blocking to false for connect 00045 result = ioctl(socket_fd, FIONBIO, &_false); 00046 if (result !=0){ 00047 throw string("Socket::Connect - Setting blocking mode failed (ioctl)"); 00048 }; 00049 //==== connect socket ======= 00050 result = connect(socket_fd, (SA*) &ServAddress, sizeof(ServAddress) ); 00051 if (result < 0) {/*error*/ 00052 throw string("Socket::Connect - Connection failed (connect)"); 00053 }; 00054 00055 //set non-blocking true for normal operation 00056 result = ioctl(socket_fd, FIONBIO, &_true); 00057 if (result !=0){ 00058 throw string("Socket::Connect - Setting non-blocking mode failed (ioctl)"); 00059 }; 00060 } 00061 00062 string Socket::Read() { 00063 int count; 00064 char buf[READBUFSIZE]; 00065 string S=""; 00066 count = recv(socket_fd, buf, READBUFSIZE,0); 00067 if (count > 0) { 00068 S.assign(buf, count); 00069 }; 00070 return S; 00071 } 00072 00073 bool Socket::Write(string& data) { 00074 int count; 00075 while (data.size() >0) { 00076 count = send(socket_fd, data.c_str(), data.size(),0); 00077 if (count!=-1) { 00078 if (count<=data.size()) { 00079 data.erase(0, count); 00080 }; 00081 } else { 00082 data=""; 00083 }; 00084 } 00085 return true; 00086 }

Generated on Thu Jun 16 15:47:18 for pc_demo.kdevelop by doxygen 1.3.8