Help with simple C chat + kqueue

Hello,

I'm writing a very simple server/client chat. At the moment I have no way of determining when data arrives in the receive buffer.

This is how the send/receive part of the chat currently looks like:


Code:
.
.
.
for(;;){

fgets(sendbuffer,sizeof sendbuf,stdin);

    send(acceptfd,sendbuffer,sizeof sendbuffer,0);

         recv(socketfd,recvbuff,sizeof recvbuff,0);
printf("%s",recvbuff);

}
This code is very primitive, I was looking for some means to determine when data were available on the listening side. After some reading about select()/poll() and performance issues I decided to try Kqueue() instead. I did only find a few example uses of Kqueue()
but this is what I tried:

Code:
struct kevent events;
struct kevent changes;

int new_event;

EV_SET(&changes,sockfd,EVFILT_READ,EV_ADD | EV_ENABLE,0,0,0);

for(;;){

new_event = kevent(kq,&changes,1,&events,1,NULL);  

if(events.flags & EVFILT_READ){
// call recv..
}

else ...
//call fgets and send 
}

Unfortunately this didn't work out very well, and I still don't think I got it right because return still has to be pressed for reading and printing data from the buffer.

How can I improve this?
Ideas and comments are welcome.
 
To start with, for proper chat client mechanics you need two threads. One handling input and second handling the receiving or otherwise you can't type while receiving or receive while typing. Just keep in mind when you get two threads working simply calling fgets on stdin will not do good as your screen will be in a mess if other client sends something while you are typing. Also kqueue is not portable, I'd go with something POSIX friendly.
 
expl said:
Just keep in mind when you get two threads working simply calling fgets on stdin will not do good as your screen will be in a mess if other client sends something while you are typing.

Ok, Maybe use some kind of input buffer?, and when data is available call the thread and print it -> sleep.
 
Threads are good but it can write console while user entering his text. You can manage this with mutexes, but it will cause lockdown... So received text should be shown it other place than input
p.s. i think kqueue is too powerful for this task ;)
 
Business_Woman said:
Ok, Maybe use some kind of input buffer?, and when data is available call the thread and print it -> sleep.

It's not about printing out, it's about reading keys. Your thread can not do anything else when it's reading keys and waiting for return to indicate end.

If you want to have a clean terminal use ncurses library with input line being somewhere separately on the bottom with text coming from top to down like on a classical chat client.

Alt said:
You can manage this with mutexes, but it will cause lockdown...

Bad idia. Locking will destroy the purpose of multiple threads (in this case).
 
Back
Top