[Tutor] simple server and client question

Deirdre Saoirse deirdre@deirdre.net
Tue, 13 Feb 2001 15:23:08 -0800 (PST)


On Tue, 13 Feb 2001, Rob Andrews wrote:

> The mandate has come from above that I write a simple server and
> client in Python in preparation for a project in development.  The
> server and client can do absolutely anything, and barely that, if I so
> choose, as they will not be used in the project (unless my code is
> brilliant enough to be useful for the project, I suppose, which is
> unlikely as it's a Java project).  The important thing is that I
> understand how to write such things.

Well, without wrapping a big abstraction around it, sometimes it's just
fun to play at the low level and see how these things work. Thus, I
recommend at least trying a very little project at the low level socket
modele WITHOUT a lot of abstraction, etc. Get your hands dirty.

With all due respect, the prior suggestion for XML-RPC is SO overkill --
a web server just blats a file out to a port after adding some headers.

Now, with that, you should be able to write a web server of your own; a
mini web server that can run from inetd.conf (i.e. one that exits right
after delivering a file) should be able to be written in a very few lines
of code.

Ok, here's a really stupid client/server pair, just for amusement and
amazement. This is an adaptation of the examples found in the library
docs.

The server opens up an unprivileged port (> 1023), in this case, 30242, on
the server localhost (aka 127.0.0.1). It waits for a client. The client,
when connected, sends the phrase "foo." The server responds "bar." The
client waits for the server. They repeat this two times, then the server
closes the connection.

Ready?

Server code:

import socket
HOST = '' # Symbolic name meaning the local host
PORT = 30242 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
count = 0
while 1:
	data = conn.recv(1024)
	if not data: break
	print "Data received:",data
	if data == 'foo':
		conn.send('bar')
		count = count + 1
	else:
		conn.send('err')

	if count == 3:
		break

print 'Closing connection to', addr s.close()

client code:

import socket
HOST = '' # Symbolic name meaning the local host
PORT = 30242 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
count = 0
while 1:
	count = count + 1
	if count == 2:
		s.send('boo!')
	else:
		s.send('foo')
	data = s.recv(1024)
	if not data: break
	print data

	if count == 4:
		break

print 'Closing connection.' s.close()

_Deirdre