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
00025
00026 bzero(&ServAddress,
sizeof(ServAddress));
00027
00028 ServAddress.sin_addr.s_addr = inet_addr(ip.c_str());
00029
00030 ServAddress.sin_port = htons(port);
00031
00032 ServAddress.sin_family = AF_INET;
00033
00034
#ifdef WIN32
00035
WSAStartup(17, &WSA);
00036
#endif
00037
00038
00039 socket_fd = socket(AF_INET, SOCK_STREAM, 0);
00040
if (socket_fd < 0) {
00041
throw "Socket::Connect - Socket creation failed (socket)";
00042 };
00043
00044
00045 result = ioctl(socket_fd, FIONBIO, &_false);
00046
if (result !=0){
00047
throw string(
"Socket::Connect - Setting blocking mode failed (ioctl)");
00048 };
00049
00050 result = connect(socket_fd, (SA*) &ServAddress,
sizeof(ServAddress) );
00051
if (result < 0) {
00052
throw string(
"Socket::Connect - Connection failed (connect)");
00053 };
00054
00055
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 }