[comp.unix.wizards] socket communication problems

sekoppenhoef@rose.waterloo.edu (09/17/89)

Can anyone help me here? I thought that SOCK_STREAM type sockets were
bidirectional in communication. Shouldn't I be able to read and write on
BOTH ends of a socket connection? The following code is part of the client
end. I want the client to get and receive info from a server. So *both*
sides need to read and write. What am i doing wrong?


	sock = socket(AF_INET, SOCK_STREAM, 0);
		.
		.
	server.sin_family = AF_INET;
	hp = gethostbyname(argv[1]);
		.
		.
	bcopy( hp->h_addr, &server.sin_addr, hp->h_length); 
	server.sin_port = htons(atoi(argv[2]));
	
	if (connect(sock, &server, sizeof(server)) < 0){
		perror("connecting to stream socket"); exit(1);
		}

**These two commands are what I'm using to write and read... the 'write' works
**on the client end but not the read, and vice versa for the server end
the server end uses an ACCEPT to get the scket name for communication of course.
		
	write(sock, buf, n) 
	read(sock,buf,sizeof(buf) ) 


HELP!


	

madd@bu-cs.BU.EDU (Jim Frost) (09/23/89)

In article <16453@watdragon.waterloo.edu> sekoppenhoef@rose.waterloo.edu writes:
|Shouldn't I be able to read and write on
|BOTH ends of a socket connection? [...]
|What am i doing wrong?
[...]
|**These two commands are what I'm using to write and read... the 'write' works
|**on the client end but not the read, and vice versa for the server end
|the server end uses an ACCEPT to get the scket name for communication of course.	
|	write(sock, buf, n) 
|	read(sock,buf,sizeof(buf) ) 

This will fix your problem:

	for (i= 0; i < sizeof(buf);)
	  i += read(sock, buf + i, sizeof(buf) - i);

How fondly I remember having this same problem, asking Barry Shein
about it, and hearing "did you check the return value from read?" and
feeling very silly.  You'll find that socket reads don't read the
whole thing much of the time.

Note that you should really do error checking in that loop, too.

jim frost
software tool & die
madd@std.com