How can I setup my sockets routine to either “send” (first) or (switch) to “receive” if data is “sent” from another computer (first)?
thanks
general code:
-(void) TcpClient{
char buffer[128];
struct sockaddr_in sin;
struct hostent *host;
int s;
host = gethostbyname("10.0.0.3");
memcpy(&(sin.sin_addr), host->h_addr,host->h_length);
sin.sin_family = host->h_addrtype;
sin.sin_port = htons(4000);
s = socket(AF_INET, SOCK_STREAM, 0);
connect(s, (struct sockaddr*)&sin, sizeof(sin));
while(1){//this is the Client sequence:
send(s, buffer, strlen(buffer), 0);//but what if the Server sends first ?? Client needs to receive here first
recv(s, buffer, sizeof(buffer), 0);
}
close(s);
}
A socket is bi-directional. It can be read from and written to at any time. If you want to write a single routine that decides when to read and when to write, you need to use the
select()function. It will tell you when a socket has data available for reading, and when the socket can accept data for sending. If the socket receives data before you have data to send, your routine can detect that and perform a “receive/send” operation. If you have data to send before the socket receives data, your routine can detect that and perform a “send/receive” operation instead. For example: