18 #include <netinet/in.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
27 #define close closesocket
29 #pragma comment(lib, "ws2_32.lib")
37 isockstream::isockstream(
int port)
41 if ( (portID = establish()) < 0)
42 cout <<
"Server couldn't be established on port "
47 int isockstream::establish()
50 char myname[] =
"localhost";
52 struct sockaddr_in sa;
55 memset(&sa, 0,
sizeof(
struct sockaddr_in));
57 hp= gethostbyname(myname);
61 cerr <<
"isockstream::establish(): gethostbyname() failed!\n"
62 <<
"isockstream::establish(): gethostname() returned: '"
63 << myname <<
"'" << endl;
68 sa.sin_family= hp->h_addrtype;
69 sa.sin_port= htons(portnum);
71 if ((port = socket(AF_INET, SOCK_STREAM, 0)) < 0)
73 cerr <<
"isockstream::establish(): socket() failed!" << endl;
79 setsockopt(port, SOL_SOCKET, SO_REUSEADDR, (
char *)(&on),
sizeof(on));
81 if (bind(port,(
const sockaddr*)&sa,(
socklen_t)
sizeof(
struct sockaddr_in)) < 0)
83 cerr <<
"isockstream::establish(): bind() failed!" << endl;
94 int isockstream::read_data(
int s,
char *buf,
int n)
103 if ((br = recv(s, buf, n - bcount, 0)) > 0)
117 void isockstream::receive(std::istringstream **in)
124 delete (*in), *in = NULL;
132 if ((socketID = accept(portID, NULL, NULL)) < 0)
134 cout <<
"Server failed to accept connection." << endl;
139 if (recv(socketID, length, 32, 0) < 0)
150 Buf =
new char[size+1];
151 if (size != read_data(socketID, Buf, size))
153 cout <<
"Not all the data has been read" << endl;
158 cout <<
"Reading " << size <<
" bytes is successful" << endl;
164 (*in) =
new istringstream(Buf);
167 isockstream::~isockstream()