I would like to make non-block TCP receiver so the cilent can send message to server periodically (i.e. update information every 10 minutes).
I test it in a local machine. 'return_status' value indicates that the 'bind, accept, connect and write' are working correctly but the read always return -1. Can someone explain on this? Thanks
Code of client side.
#define CONTROLPORT 6000
int main(void)
{
int control_sock, return_status;
struct sockaddr_in control_addr;
socklen_t control_len;
memset(&control_addr, 0, sizeof(control_addr));
char control_message[10];
control_sock = socket(AF_INET, SOCK_STREAM, 0);
control_addr.sin_family = AF_INET;
control_addr.sin_addr.s_addr = inet_addr("192.168.16.133");
control_addr.sin_port = htons(CONTROLPORT);
return_status = bind(control_sock, (struct sockaddr *) &control_addr, sizeof(control_addr));
fcntl(control_sock, F_SETFL, O_NONBLOCK);
return_status = listen(control_sock, 1);
cout << return_status << endl;
return_status = accept(control_sock, (struct sockaddr *) &control_addr, &control_len);
cout << return_status << endl;
while(1){
return_status = read(control_sock,control_message,sizeof(control_message));
cout << return_status << endl;
}
}
Code of sender side
#define CONTROLPORT 6000
using namespace std;
int main(void)
{
int control_sock, return_status;
struct sockaddr_in control_addr;
socklen_t control_len;
memset(&control_addr, 0, sizeof(control_addr));
char control_message[10];
control_message[10] = 111;
control_sock = socket(AF_INET, SOCK_STREAM, 0);
control_addr.sin_family = AF_INET;
control_addr.sin_addr.s_addr = inet_addr("192.168.16.133");
control_addr.sin_port = htons(CONTROLPORT);
return_status = connect(control_sock, (struct sockaddr *) &control_addr, sizeof(control_addr));
cout << return_status << endl;
return_status = write(control_sock,control_message,sizeof(control_message));
cout << return_status << endl;
}