Client with select.select()

Donn Cave donn at u.washington.edu
Mon Jun 12 13:32:45 EDT 2000


Quoth "A[r]TA" <arta at NOSPAMx-stream.nl>:
| What's wrong?
| I have some simple server programmed for experiments. You can chat with it.
| blabla.
| But with the code below, I want to connect with it. In the beginning it
| prints a welcome message.
| Or, it's meant to do. But it only prints the first line from the
| welcome-message and not the
| following. What am I doing wrong? Because in the logfile from my server,
| there's  a line
| in which stands that a login-connection has been made. So that's good.
| But what am I doing wrong? I want the whole message printed, not the first
| line.

The file object you make with makefile() is an input buffer.  When
you invoke readline() on that buffer, it fills itself with whatever
data it can get from its source, the socket, and then gives you the
first line of that data.  Then you throw away the file object, and
the rest of the data from the socket goes with it.

You probably would be better off without the file object.  Use s.recv()
to read from the socket, and string.split(text, '\n') to separate the
lines.  If the last string isn't empty, save it and append the first
string next time around.

I think you also may have the wrong idea about the write-set parameter
to select().  The test with select() is ``will I block?''  That is,
if read-set returns a file descriptor, you may read from that descriptor
without blocking - either there's data, or end of file or whatever may
cause a non-blocking state on a blocking descriptor.  The same is true
of the write set, mutatis mutandi.  The reader on the other end will
probably ignore what you're writing, you just won't block.  Sockets
are usually in this state.  I guess it's a good thing to check anyway,
but by no means is there any implication that the other end of the socket
has requested data.  ("block" means "wait".)

While I'm at it - chr(13) + '\n' is more conveniently spelled '\r\n'.

	Donn Cave, donn at u.washington.edu
----------------------------------------
| from socket import *
| from select import *
|
| s = socket(AF_INET, SOCK_STREAM)
| s.connect('127.0.0.1', 23)
| text = ''
|
| while 1:
|     q = [s.fileno()]
|     rd, wr, er = select(q, q, [], None)
|
|     for n in rd:
|         if n == s.fileno():
|             print rd, wr, er, q
|             text = s.makefile().readline()
|             print text
|
|     for n in wr:
|         if n == s.fileno():
|             g = 'password' +chr(13)+ '\n'
|             s.send(g)



More information about the Python-list mailing list