c - Trying to understand logic behind network communication -


in c, receive/send data do(roughly):

server:

  • create socket
  • bind socket port
  • listen
  • accept
  • receive send data

on client side:

  • create socket
  • connect
  • receive send

my question comes after server has done accept.

imagine after accept on server side there 3 separate lines send data:

connfd = accept(listenfd, (struct sockaddr*)null ,null); write(connfd, var1, var1size); write(connfd, var2, var2size); write(connfd, var3, var3size); 

does mean on client side need have 3 reads? this:

read(sockfd, &x, size1); read(sockfd, &y, size2); read(sockfd, &z, size3); 

in other words how should send , receive calls correspond on server , client side? should each send corresponding receive on client side?

what if on client side, after 3 read calls(like above), want send data server? shall add 1 new send , 1 new receive on client , server side respectively?

should these send/receives happening within single accept call context?

here image better illustrate kind of scenario interested in:

enter image description here

pseudo code explaining how handle kind of connections welcome.

unless working protocol has concept of "messages", e.g. udp, have stream of bytes. can send , receive them way wish.

you could, example, send 2 16-bit integers , receive them 1 32-bit integer. not intended it's legal , used time in situations is needed. can compose data structures on either side (sending , receiving) independandly, long makes sense application.

your bytes sent in order of write()'s , receive them in same order. i.e.

send(var1)  --->  recv(var1) send(var2)  --->  recv(var2) 

there no way in normal tcp (barring unused edge cases i'll not specify because nobody should use them) receive var2 before var1.

tcp communication bi-directional: each end-point (client , server) can send @ same time. , application decide when send , when receive. sending , receiving buffers independant: can send few bytes, receive few, send more... , there no interference between them (i.e. not "overwrite" receive buffer sending data nor vice versa).

i'll repeat again: have in tcp stream of bytes. tcp doesn't know , doesn't care how these bytes structured, neither on sending nor on receiving side. it's all you. when send integer or data structure, sending memory dump of those, as bytes.

for example, there's common error attempt send() data structure , because sending buffers full, system make partial write. if not check return status of send() call detect situation , send remainder of bytes by yourself, in send() call, client stuck in recv() when expects full structure , receives part of it, if specify msg_waitall.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -