Socket Confusion

by JS

I recently had some fun trying to figure out socket programming with Python. Following the example on the Python website, I wrote the following simple “server.”

import os, sys
import SocketServer
 
class SerialPortHandler(SocketServer.BaseRequestHandler):
 
    def setup(self):
        print "Setup is called..."
 
    def handle(self):
 
        self.data = self.request.recv(4096)
        print "%s wrote:" % self.client_address[0]
        print self.data
        self.request.send(self.data.upper())
 
    def finish(self):
        print "Finish is called..."
 
if __name__ == "__main__":
 
    HOST, PORT = sys.argv[1], int(sys.argv[2])
    server = SocketServer.TCPServer((HOST, PORT), SerialPortHandler)
    server.serve_forever()

Now the example client on the website only sends and receives once. I, being new to socket programming, thought I could send repeated requests by repeating my call to send:

import socket
import sys,time
 
HOST, PORT = sys.argv[1], int(sys.argv[2])
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
 
print sock.send("Sending Text One")
print sock.recv(1024)
 
print sock.send("Sending Text Two")
print sock.recv(1024)
 
print sock.send("Sending Text Three")
print sock.recv(1024)
 
sock.close()

Here’s the output from the server:

$ python test_server.py localhost 9999
Setup is called...
127.0.0.1 wrote:
Sending Text One
Finish is called...

Here’s the output from the client:

$ python test_client.py localhost 9999
16
SENDING TEXT ONE
16

Traceback (most recent call last):
  File "test_client.py", line 20, in 
    print sock.send("Sending Text Three")
socket.error: (32, 'Broken pipe')

What went wrong?