[Tutor] waiting for a particualr string from a socket

Rodrigues op73418 at mail.telepac.pt
Sun Aug 17 13:46:50 EDT 2003



> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On
> Behalf Of G Kiran
> Sent: domingo, 17 de Agosto de 2003 8:22
> To: python tutor
> Subject: [Tutor] waiting for a particualr string from a socket
>
>
> I am reading from a socket and need to wait till a
> particular string arrives
>
> s=socket(AF_INET,SOCK_STREAM)
> s.listen(5)
> conn,recv=s.connect()
>   while (1):
>         waitonsocket(conn,"START")
>         blah
>         blah
>         blah
>
>
> presently i implemented a string queue of length of string
> i am waiting for
> and i repeatedly read one byte/char at time from the socket
> and add it to
> the queue
> and check whether queue contains the string i am looking
> for...is there a
> faster way of doing this
>
> reading one char at a time and adding and checking the
> queue slows down the
> program
>

Hmmm, why don't you just buffer the recv calls and use s.find?
Something like

#A hint to the recv call.
HINT = 1024
string_to_find = "START"

#A list to buffer what we have scanned already.
lst = []
s = conn.recv(HINT)
#Enter loop.
while s.find(string_to_find) == -1:
    #Start may come in the middle of 2 packets so we break s
    #in a safe way, e.g. we leave the last len(string_to_find)
    #characters.
    lst.append(s[:-len(string_to_find)])
    #recv call.
    s = s[-len(string_to_find):] + conn.recv(HINT)


This gives you the general idea of how to go, but notice that there
are improvements that need to be made. For example, the calls from
recv may return '' indicating that the connection was closed on the
other end, etc.

HTH, with my best regards,
G. Rodrigues




More information about the Tutor mailing list