Learning Python Network Programming

(Sean Pound) #1

Client and Server Applications


if __name__ == '__main__':
listen_sock = tincanchat.create_listen_socket(HOST, PORT)
addr = listen_sock.getsockname()
print('Listening on {}'.format(addr))

while True:
client_sock, addr = listen_sock.accept()
print('Connection from {}'.format(addr))
handle_client(client_sock, addr)

This is about as simple as a server can get! First, we set up our listening socket with
the create_listen_socket() call. Second, we enter our main loop, where we listen
forever for incoming connections from clients, blocking on listen_sock.accept().
When a client connection comes in, we invoke the handle_client() function, which
handles the client as per our protocol. We've created a separate function for this
code, partly to keep the main loop tidy, and partly because we'll want to reuse this
set of operations in later programs.


That's our server, now we just need to make a client to talk to it.


A simple echo client


Create a file called 1.2-echo_client-uni.py and save the following code in it:


import sys, socket
import tincanchat

HOST = sys.argv[-1] if len(sys.argv) > 1 else '127.0.0.1'
PORT = tincanchat.PORT

if __name__ == '__main__':
while True:
try:
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print('\nConnected to {}:{}'.format(HOST, PORT))
print("Type message, enter to send, 'q' to quit")
msg = input()
if msg == 'q': break
tincanchat.send_msg(sock, msg) # Blocks until sent
print('Sent message: {}'.format(msg))
Free download pdf