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){
102 if ((br = recv(s, buf, n - bcount, 0)) > 0)
116 void isockstream::receive(std::istringstream **in)
122 delete (*in), *in = NULL;
127 if ((socketID = accept(portID, NULL, NULL)) < 0)
129 cout <<
"Server failed to accept connection." << endl;
134 if (recv(socketID, length, 32, 0) < 0)
143 Buf =
new char[size+1];
144 if (size != read_data(socketID, Buf, size))
145 cout <<
"Not all the data has been read" << endl;
148 cout <<
"Reading " << size <<
" bytes is successful" << endl;
153 (*in) =
new istringstream(Buf);
156 isockstream::~isockstream()