Simple client - receiving data from server and keyboard w/o blocking
Hi everyone. I'm building a simple chat server/client using c++ and Winsock and I've run into a problem with my client. I'm combining two examples from Beej's Networking Guide to try and use select() to accept input from the keyboard if there is nothing to receive.
Here's my code (stripped down):
Code:
#include <string>
#include <iostream>
#include <winsock.h>
#define STDIN 0
void error (const char * error) {
std::cout<<"Error with "<<error<<"\n"<<WSAGetLastError();
}
int main(int argc, char *argv[]) {
SOCKET sockfd;
// ....
// whole bunch of initialisation stuff
// ....
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
error("socket");
exit(1);
}
// etc
// ......
fd_set readfds;
fd_set master;
FD_ZERO(&master);
FD_ZERO(&readfds);
FD_SET(STDIN, &master);
FD_SET(sockfd, &master);
// ....
int nbytes;
timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 500000;
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
error("connect");
return 1;
}
while (1) {
readfds = master;
if (select(sockfd+1, &readfds, NULL, NULL, &tv) == -1) {
error("select");
return 1;
}
for (int i = 0; i <= sockfd; i++) {
if (FD_ISSET(i, &readfds)) {
if (i == STDIN) {
// don't think i should be using cin here. how do i do it?
std::cin>>message;
// ...
send(sockfd, sendbuffer.c_str(), length, 0);
} else {
// receive data from server?
nbytes = recv(i, recvbuffer, 1, 0);
// ...
}
}
}
}
return 0;
}
If you need more code just tell me, I've tried to take out all the irrelevant stuff. Any help would be greatly appreciated. :)