Click to See Complete Forum and Search --> : dont want blocking receive message


LiteUponLite
October 27th, 2004, 12:38 AM
Hi,

I'm programming a client for a chatting program and I had a question about the client, when it receives messages. My Client is allowed to have only one connection with the server. I have many receive function calls but i know when they will be executed so i've called them at appropriate location in the code, except for broadcast message which server can send any time to the client.

Now, i can't just call the receive message function as its a blocking call and any code below it wont' be executed....

I can't use the 'select' function either as it creates new socket descriptors and new connections and i'm allowed to have only one connection with server...

I can't use fork to invoke another thread cuz i'll have receive calls (like i mentioned earlier) both in the child and parent process so when a server sends message either running thread can get it. However, i only want the receive call in the parent to be executed, whose purpose is to catch broadcast messages....

Someone told me to use fcntl() however, i'm having problems understanding how it functions and what its purpose is :S...if someone can plz explain that or give a link for a good tutorial on it, besides the man pages :) or if there's a better solution to the whole problem


Thanks a lot,
Samar

LiteUponLite
October 27th, 2004, 12:49 AM
basically i want to know if non-blocking receive message function will solve the problem, if so what to call and how...thnxs

Mathew Joy
October 27th, 2004, 04:44 AM
You have to restructure you code. When you call recv() if the socket is in a blocking mode then it waits for the message there itself. If it is in a non-blocking mode, then you there won't be any waiting. But if the data is not present at the moment, then the recv() will return with error. So you have to use appropriate notifiers like select(). This is good only if you are using more than one client, otherwise blocking call would do. (I assume you are not using windows). It is always better to keep the communication part separate from the application code, like by using threads for instance.

BTW select() doesn't create any sockets.

NMTop40
October 27th, 2004, 08:10 AM
fork() does not create a new thread it creates a new process.

If you want to create a new thread then do so with pthread_create().

And if you did it this way then one thread would probably be used to block with recv() and perhaps write to some formatted internal buffer (some data structure such as std::queue) when it receives messages, while the other thread can periodically check this buffer without blocking. You will need a mutex to protect this buffer, but of course the thread doing the recv() will only have the mutex when it intends to write and will then unlock the mutex before it goes into recv() again, so it will not cause the other thread to block for any noticeable period of time.