Simultaneous socket i/o

Started by
1 comment, last by hplus0603 17 years, 12 months ago
I've been trying about a million different ways to handle simultaneous socket I/O in attempt to create the client side of a chat client I'm working on. The problem I'm facing lies in the fact that any function that deals with input streaming is blocking (cin, fgets, etc.). The problem with this is that the only way I can get clients to chat is in a HIGHLY synchronous fashion (i.e. client A sends, client B receives and then sends, client A receives and then sends, etc.) Is there any way to make it so that I can send messages while still RECEIVING messages from the other client? That is, any way that doesn't involve multithreaded programming (which wholly intimidates me). My current implementation involves the client establishing a connection with a server that handles all client connections, and then the client enters an infinite while loop that looks something like this: while(1) { // Perform some type of input n = select( FD_SETSIZE, &readfds, NULL, NULL, NULL ) //... etc. } I've tried setting both stdin and the socket file descriptor in readfds and then makin stdin nonblocking, but this didn't work. I've tried about a million simpler things, but to no avail. Thanks in advance!
Advertisement
You need to do the processing asynchronouslly, doing this is doing things in different thread but probebly not multithreading as you think of it.

Not sure what language and protocal you are using or I would give you a little example. But look up (your langauge), (your protocal), and asynchronous. This should give you the information you need.

Hope this helps.
theTroll
Even synchronous sockets are non-blocking if select() tells you there is data on them. That is, if select() says that socket X has some data, the next call to recv() will return at least one byte, and will not block. This is the difference between recv() and read(), btw. recv() COULD still return 0, if the other end has disconnected, but it's guaranteed to not block at that point.

Thus, your typical loop looks like:

  select()  foreach (s in writeable sockets) {    w = sendto(sockets.outbuffer, sockets.outpos, s, …);<br>    sockets.advance_write(w);<br>  }<br>  foreach (s in readable sockets) {<br>    r = recvfrom(sockets.inbuffer+sockets.inpos, sockets.size-sockets.inpos, s, …);<br>    sockets.inpos += r;<br>    if (l = is_complete_message(sockets.inbuffer, sockets.inpos)) {<br>      handle_message( sockets.inbuffer, l);<br>      sockets.advance_read(l);<br>    }<br>  }<br></pre><br><br>The implementation of advance_… could easily just use memmove() remove the used data from the buffer, and subtract the size from the position.<br><br><a href='http://www.mindcontrol.org/etwork/'>Etwork</a> contains buffer code for managing all of this for you, if you want.<br>
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement