1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
|
#include "socket.h"
#include <iostream>
int Socket::nofSockets_= 0;
void Socket::start() {
if (!nofSockets_) {
WSADATA info;
if (WSAStartup(MAKEWORD(2,0), &info)) {
throw "Could not start WSA";
}
}
++nofSockets_;
}
void Socket::end() {
WSACleanup();
}
Socket::Socket() : s_(0) {
start();
// UDP: use SOCK_DGRAM instead of SOCK_STREAM
s_ = socket(AF_INET,SOCK_STREAM,0);
if (s_ == INVALID_SOCKET) {
throw "INVALID_SOCKET";
}
refCounter_ = new int(1);
}
Socket::Socket(SOCKET s) : s_(s) {
start();
refCounter_ = new int(1);
};
// Clear socket
Socket::~Socket() {
if (! --(*refCounter_)) {
close();
delete refCounter_;
}
--nofSockets_;
if (!nofSockets_) end();
}
// Create socket
Socket::Socket(const Socket& o) {
refCounter_=o.refCounter_;
(*refCounter_)++;
s_ =o.s_;
nofSockets_++;
}
// Set socket
Socket& Socket::operator=(Socket& o) {
(*o.refCounter_)++;
refCounter_=o.refCounter_;
s_ =o.s_;
nofSockets_++;
return *this;
}
// Close connection
void Socket::close() {
closesocket(s_);
}
// Get bytes
std::string Socket::receiveBytes() {
std::string ret;
char buf[1024];
while (1) {
u_long arg = 0;
if (ioctlsocket(s_, FIONREAD, &arg) != 0)
break;
if (arg == 0)
break;
if (arg > 1024) arg = 1024;
int rv = recv (s_, buf, arg, 0);
if (rv <= 0) break;
std::string t;
t.assign (buf, rv);
ret += t;
}
return ret;
}
// Get a string line
std::string Socket::receiveLine() {
std::string ret;
while (1) {
char r;
switch(recv(s_, &r, 1, 0)) {
case 0: // not connected anymore;
// ... but last line sent
// might not end in \n,
// so return ret anyway.
return ret;
case -1:
return "";
}
ret += r;
if (r == '\n') return ret;
}
}
// Send line
void Socket::sendLine(std::string s) {
s += '\n';
send(s_,s.c_str(),s.length(),0);
}
// Send bytes
void Socket::sendBytes(const std::string& s) {
send(s_,s.c_str(),s.length(),0);
}
|