6 Network::Network(int newPort) : sfd(-1), port(newPort), file(NULL)
8 sfd = socket(PF_INET, SOCK_STREAM, 0);
11 perror("Network::Network - Error creating TCP socket");
20 if (shutdown(sfd, SHUT_RDWR) == -1)
22 perror("Network::~Network - shutting down socket... ");
30 Server::Server(int newPort) : Network(newPort)
32 struct sockaddr_in name;
37 name.sin_family = AF_INET;
38 name.sin_addr.s_addr = htonl(INADDR_ANY);
39 name.sin_port = htons(port);
41 if (bind( sfd, (struct sockaddr *) &name, sizeof(name) ) < 0)
43 perror("Server::Server - Error binding socket");
48 if (listen(sfd,1) < 0)
50 perror("Server::Server - Error listening on socket");
54 int psd = accept(sfd, 0, 0);
59 perror("Server::Server - Error accepting connection");
69 cc=recv(sfd,buf,sizeof(buf), 0) ;
70 if (cc == 0) exit (0);
72 printf("message received: %s\n", buf);
77 Client::Client(const char * serverAddress, int newPort) : Network(newPort)
79 struct sockaddr_in server;
83 server.sin_family = AF_INET;
84 hp = gethostbyname(serverAddress);
85 bcopy ( hp->h_addr, &(server.sin_addr.s_addr), hp->h_length);
86 server.sin_port = htons(port);
88 if (connect(sfd, (struct sockaddr *) &server, sizeof(server)) < 0)
90 fprintf(stderr, "Client::Client - Error connecting to server at address %s: ", serverAddress);
101 send(sfd, "HI", 2,0 );
108 * Sends a message accross the network
109 * WARNING: Always terminates the message with a newline '\n'
110 * @returns true if the message was successfully sent; false if it was not (ie: the network was not connected!)
112 bool Network::SendMessage(const char * print, ...)
114 if (!Valid()) //Is the process running...
119 file = fdopen(sfd, "r+");
126 if (vfprintf(file, print, ap) < 0 || fprintf(file, "\n") < 0)
137 * Retrieves a message from the network, waiting a maximum amount of time
138 * @param buffer - C++ string to store the resultant message in
139 * @param timeout - Maximum amount of time to wait before failure. If timeout <= 0, then GetMessage will wait indefinately.
140 * @returns true if the response was recieved within the specified time, false if it was not, or an EOF was recieved, or the process was not running.
142 bool Network::GetMessage(string & buffer, double timeout)
144 if (!Valid() || timeout == 0)
149 file = fdopen(sfd, "r+");
153 assert(&buffer != NULL);
154 GetterThread getterThread(file, buffer);
155 assert(&(getterThread.buffer) != NULL);
157 TimerThread timerThread(timeout*1000000);
159 getterThread.Start();
164 while (!getterThread.Finished())
166 if (timeout > 0 && timerThread.Finished())
180 if (buffer.size() == 1 && buffer[0] == EOF)