Now that you have a basic understanding of how a socket can work, we will create our own custom server and another client so that we have full control over both parts of the transaction.
All the examples that we have created so far have been more or less demonstrative in nature. Let's start building something larger and more functional now, and also re-use some code from Chapter 2, Input and Output, as well. We will need to modularize some of our previous code so that they can be easily re-used and extended.
Create a file called server_socket.py
. This utility class won't do much by itself; its sole purpose will be to set up and manage the incoming socket connections. First, let's define a method called initialize_server
. In it, we create and bind a socket in much the same way as we did in the client:
def initialize_server(host, port): print "Starting server on %s:%s" % (host,port) srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Set the socket reuse to 1, so that...