select(), sending and receiving data
- From: Markus Pitha <markus@xxxxxxxxxx>
- Date: Mon, 26 Dec 2005 10:32:00 +0000
Hello,
I'm trying to write a little server and a corresponding client. The
server runs without any problems. I tried to connect with telnet and the
telnet client was able to receive the "Welcoming messages" of the server
as well as I could see the typed data of the client appearing on the
server stdout, as it was intended.
Unfortunately I have problems with my client. I am able to send data to
the server, but I can not receive any data. After my research I came to
the conclusion that select() would be able to handle this, but obviously
I did do something wrong.
Can anybody tell me why I can not receive any data from the server? (So
recv() doesn't work in the program, but send() works)
Here is the client script:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
int main(int argc, char *argv[]) {
int sock, bytes;
struct sockaddr_in srv;
char stdinbuffer[256];
fd_set readfds, writefds;
struct timeval tv;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
tv.tv_sec = tv.tv_usec = 0;
if (argc != 3) {
fprintf(stderr, "usage: %s host port\n", argv[0]);
return 1;
}
if ( (sock = socket(AF_INET, SOCK_STREAM, 0) ) == -1 )
perror("socket failed()");
srv.sin_family = AF_INET;
srv.sin_addr.s_addr = inet_addr(argv[1]);
srv.sin_port = htons( (unsigned short int) atol(argv[2]) );
if (connect(sock, (struct sockaddr *)&srv, sizeof(srv)) == -1)
perror("connect failed()");
FD_SET(sock, &readfds);
FD_SET(sock, &writefds);
while (1) {
select(sock+1, &readfds, &writefds, NULL, &tv);
if (FD_ISSET(sock, &readfds) ) {
while (bytes = recv(sock, stdinbuffer, sizeof(stdinbuffer), 0 ) ) {
if (bytes == -1)
perror ("recv() in FD_ISSET");
stdinbuffer[bytes] = '\0';
printf("%s", stdinbuffer);
}
}
if (FD_ISSET(sock, &writefds) ) {
printf("> ");
fgets(stdinbuffer, 255, stdin);
if (send(sock, stdinbuffer, strlen(stdinbuffer), 0 ) == -1)
perror("Error sending to socket within FD_ISSET");
if (stdinbuffer[0] == '\n')
break;
}
}
close(sock);
return 0;
}
.
- Follow-Ups:
- Re: select(), sending and receiving data
- From: Pascal Bourguignon
- Re: select(), sending and receiving data
- Prev by Date: Re: select(), sending and receiving data
- Next by Date: Watch Window
- Previous by thread: Re: Is it possible to write Unix for Unix ???
- Next by thread: Re: select(), sending and receiving data
- Index(es):
Relevant Pages
|