tags:

views:

37

answers:

2

I have the typical Chat aplication.

The Client side is implemented using two Threads.

Thread1

do {

 show menu
 read option
 case option
  1: option1
  2: option2
  .
  .
  . 
  5:end
     end case
while (!end)

Thread 2:

do {

 read message from socket
 display message
while (!end)

One problem is the Thread1 being to fast, so after procesing the option it displays the menu again before the Thread2 can display it's message. I have solve this by puting Thread1 to sleep for 1000ms, but don't know if there is a better way to do this.

The other one is: when a client is doing nothing, there is just a message on screen asking for a option to process. If another Client send him a message, then this message displays after the promt, so the info is messy: here is an example of what a Client will see after getting a message from another client.

1.- Print users conected  
2.- Send message to all  
3.- Send message to a user  
4.- Quit  
Choose an option: Message received from user "david": hello!  

Is there any way to deal with this?

A: 

If your threads communicate with a pipe, you can have the first thread wait for the second to say "I'm done."

Jamer
+1  A: 

your first problem can be solved with thread synchronization. It is a heavy subject but threads are in general so brace yourself for some learning

Thread 1
wait for user to make a choice
user makes a choice
process -> notifies thread 2 of processing
wait for thread 2 to be ok
wait for user to make a chocie

Thread 2
wait for processing from thread 1
sends data via socket
notifies thread 1 that it's ok
wait for processing from thread 1

your second problem can be solved with gui. There are not many console based chat programs and there is a reason for that. unix systems have ncurses to deal with text positionning in the console but windows only have hacks equivalent of ncurses. You might want to check it out

Eric
I tried with synchronization , but wasn't sure if synchronize, and wait() and notify() where the right tools for the subject.I will try the GUI aproach later, but I was just curious to see if there was something to deal with that.
David Casillas