recv
Gerhard Häring
gh at ghaering.de
Wed Jun 18 04:16:48 EDT 2003
Oleg Seifert wrote:
> Hallo Leute,
>
> habe eine kleine Frage:
>
> Ich soll mit Python eine Netzwerkanfrage senden und eine Antwort
> ausgeben. Dafür habe ich folgenden Skript geschrieben:
"""
Hi folks,
I have a little question:
I'm supposed to send a network request using Python and print a
response. I've written the following script for this:
"""
> -------------------------------------
> from socket import *
>
> def read():
> print s.recv(1024)
>
>
> s = socket(AF_INET, SOCK_STREAM)
> s.connect(("localhost", 99))
>
> s.send("loadGraph(\"g.g\");\n")
> read()
> s.close()
> -------------------------------------
> Die Anfrage wird gesendet und die Antwort kommt auch an, aber von dem
> Antwort erscheint immer nur eine Zeile. Die Antworte sind auch
> unterschiedlich, sie können verschiedene Zeilenanzahl haben. Wie kann
> ich unabhängig von einer Antwortstruktur, ganze Antwort ausgeben ?
"""
The request is sent and the response arrives as well, but from the
response I only ever see one line. The responses are different as well,
they can have different number of lines. How can I print the whole
response, independent of the structure (numer of lines) of the response?
"""
If you want to roll your own protocol, you need to design it in a way
such that the client *can* know when a response is finished. Also it's
easier to make the socket a file and read from that. Here's a snippet
from the module smtplib in the standard library that shows how it's can
be done:
#v+
if self.file is None:
self.file = self.sock.makefile('rb')
while 1:
line = self.file.readline()
if line == '':
self.close()
raise SMTPServerDisconnected("Connection unexpectedly
closed")
if self.debuglevel > 0: print 'reply:', `line`
resp.append(line[4:].strip())
code=line[:3]
# Check that the error code is syntactically correct.
# Don't attempt to read a continuation line if it is broken.
try:
errcode = int(code)
except ValueError:
errcode = -1
break
# Check if multiline response.
if line[3:4]!="-":
break
#v-
Continuation lines look like these:
#v+
250-mail.w-koerting.de
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-AUTH LOGIN PLAIN CRAM-MD5 GSSAPI DIGEST-MD5
250-AUTH=LOGIN PLAIN CRAM-MD5 GSSAPI DIGEST-MD5
250-XVERP
#v-
Then comes a line in a different format so the SMTP client knows it's
the last one in the response:
#v+
250 8BITMIME
#v-
HTH & HAND,
-- Gerhard
More information about the Python-list
mailing list