Client/server chat program

Jonathan Gardner jgardn at alumni.washington.edu
Mon Dec 10 22:38:26 EST 2001


On Tuesday 11 December 2001 06:19 am, neuromorphus wrote:
> <b>Statement</b>
>
> I'm creating a client/server chat program on my Linux system. It's a
> group chat like ICQ, so all messages go through the server and then
> broadcasted to online users. Note: for the time being, this program
> will operate in a <b>terminal/console</b>, so no gui.
>
> <b>Problem</b>
>
> The client program continuously asks for 'raw_input' from the user,and
> then sends the msg to the server to be broadcasted. However, I can't
> output messages to the terminal/console, if the client program is
> waiting for input. What happens is that after the client types a
> message. All previous output(of other users) are then flush to
> that client's screen. In other words, how do i get client input and
> display current messages to the client's screen without having to wait
> for the clients input. NOte: this is a terminal.
>
> Telnet does it some kinda way(it works perfect), but i'm trying to get
> my client to work the same way.
>

You'll need to use non-blocking reads and writes. (Don't know if such a thing 
exists like you need it in Windows). What your program will look like is this:

while 1:
    # Is anything ready to be read from (socket or std_in?)
    # if so, read it in.
    # Is there any pending output? (to std_out or to the socket?)
    # if so, write it out.

Whenever your program wants to send a message to the socket or to std_out, 
just append it to the output string.  So, for the above example, where 
whatever the guy types goes to the server, just take whatever is coming in on 
std_in and append it to the string that represents what you are sending out 
to the socket (and vice-versa for input from the server).

Note that you may not be able to write everything out in one pass, so there 
may be leftovers from the last attempt to write everything. Oh well, you just 
have to wait until it is ready to be written to again.

This will go for both the server and client. There are a number of useful 
pieces of code on the internet. I wrote something a long time ago that does 
what you need... take a look at http://sf.net/projects/simpymud/ in the CVS 
repository. I forget what does what, but it shouldn't be too hard to figure 
out. 

BTW, I think the server is the hard part. You already have a useful client in 
telnet. If you want a customized client, then work on that *after* you get 
the server figured out.

Jonathan




More information about the Python-list mailing list