TCP connection. How to make the client only send data at the moment of the server's read()?
I have a client in iPod iOS 4.3 and a server in Linux C. I can make a TCP connection and transfer data.
The server runs in a cycle with read() and printf.The client should send data only when asked. I found out that even after one read(), printf and halting at a getchar(), the client (iPod) is still getting the messagem NSStreamEventHasSpaceAvailable and sends the data.
After i press any key on the server, it gets to the read() again, and shows much more data. I just wanted some help about the synchronous/asynchronous and blocking/non-blocking setting i should use in both the client and server. (theoretical, thus no need for coding, i guess.)
As requested, here is the server code:
void testApp::setup() {
int portno;
struct sockaddr_in serv_addr;
socklen_t clilen;
connection = 0; //Still no connection
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi("50000");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
}
void testApp::update() {
int check = 0;
int n;
char buffer[256];
if(connection != 0)
{
check = recv(newsockfd, buffer, 256, MSG_PEEK|MSG_DONTWAIT);
}
/*
developerweb.net/viewtopic.php?id=5627
*/
if(connection == 0 /*1st connection*/ | check == 0 | (check < 0 && errno != EAGAIN))
{ printf("CHECK é %d",check);
if(connection != 0)
{ close(newsockfd); newsockfd = -1; printf("Client disconnected.\n");}
printf("\n\n-=Waiting for connection...=-\n");
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);
printf("\nClient connected successfuly! \n");
}
if (newsockfd < 0) {printf("ERROR on accept"); close(newsockfd); newsockfd=-1; }
else if(newsockfd == 0) printf("No socket\n");
else
{
printf("Waiting for message...\n");
connection = 1;
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message开发者_运维技巧: %s\n",buffer);
}
printf("\nPress any key to continue...");
getchar();
}
Thanks for any help.
Don't worry about coordinating between client and server -- that would require sending data back and forth, which would presumably require more coordinating... It becomes a circular problem. Just have the client send it's data and have the server read until there's no more data. The lower level networking software will queue up any data that comes in between reads, so you won't miss anything.
It is impossible for the client to know if the server is ready to read unless the server informs the client of that.
Instead of pushing out messages from the client, wait for a request from the server.
精彩评论