Learning Python Network Programming

(Sean Pound) #1
Chapter 8
msg = tincanchat.recv_msg(sock) # Block until
# received complete
# message
print('Received echo: ' + msg)
except ConnectionError:
print('Socket error')
break
finally:
sock.close()
print('Closed connection to server\n')

If we're running our server on a different machine from the one on which we are
running the client, then we can supply the IP address or the hostname of the server
as a command line argument to the client program. If we don't, then it will default to
trying to connect to the localhost.


The third and forth lines of the code check the command line arguments for a server
address. Once we've determined which server to connect to, we enter our main loop,
which loops forever until we kill the client by entering q as a message. Within the
main loop, we first create a connection to the server. Second, we prompt the user
to enter the message to send and then we send the message using the tincanchat.
send_msg() function. We then wait for the server's reply. Once we get the reply,
we print it and then we close the connection as per our protocol.


Give our client and server a try. Run the server in a terminal by using the
following command:


$ python 1.1-echo_server-uni.py


Listening on ('0.0.0.0', 4040)


In another terminal, run the client and note that you will need to specify the server if
you need to connect to another computer, as shown here:


$ python 1.2-echo_client.py 192.168.0.7


Type message, enter to send, 'q' to quit


Running the terminals side by side is a good idea, because you can simultaneously
see how the programs behave.


Type a few messages into the client and see how the server picks them up and
sends them back. Disconnecting with the client should also prompt a notification
on the server.

Free download pdf