[Tutor] sockets

Rob Hudson rob@euglug.net
Wed Jul 9 20:22:05 2003


Hello,

I'm new to the list.  I'm taking a class at the local community college.
I work as a PHP coder doing web design and have learned Perl in the
past.  Python looked intriguing and so far I'm having fun with it.  I'm
from Oregon if anyone else here is nearby.  Anyway, here's my
question...

While reading a Randall Schwartz article on Perl and sockets[1], I decided
to rewrite his little perl code in python.  Here's the code:

#!/usr/bin/env python
import sys
from socket import *

if len(sys.argv) != 2:
    exit

host = sys.argv[1]
port = int(sys.argv[2])

# Create a socket
# AF_INET means the IP address protocol
# SOCK_STREAM means the TCP transfer protocol
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.connect((host, port))

data = sockobj.recv(1024)

print 'response from', host, 'port', port, 'was:'
print data

sockobj.close()


I call it like this:
python socket-test.py 132.163.4.203 13


My question is:  What if the data the server sends is more than 1024
bytes?  Python can't do this, right?

while (recv = sockobj.recv(1024)):
    data += recv

Specifically, I think Python can't make an assignment inside a
conditional.  Would you get the data, then check for NULL and break if
the data is empty?  Or check for EOF?  Something like that?

This code actually works since the data returned is small.  The other
thing to note is that since time servers don't expect any starting
message, they just send the time automatically and kill the socket.
That's why I don't need a sockobj.send(message) call.

Thanks!
-Rob

[1] http://www.stonehenge.com/merlyn/UnixReview/col47.html