Hello! Today's blog post will be about coding a very rudimentary Client and Server application duo, which will communicate by using TCP Sockets.
It is, as illustrated, in principle, just two cans and a string that ties them together. The server will listen for clients and accept incoming data, while the client will, upon startup, check for the server on a predefined port and if found, will enable you to send messages! If not, it will simply exit with an exception.
For a more substantial read about TCP/IP, refer to this Wiki article. It should be sufficient and cover the basics of the model.
Step 1 Server Application
This is going to be our receiving end (no puns, please) of the duet.
#!C:\python27 #Replace with usr/bin/ clause for Linux
import SocketServer #imports the socket server library
class EchoHandler( SocketServer.StreamRequestHandler ): #declares the class
def handle(self): #installs handler
input= self.request.recv(1024) #defines request buffer
print "Input: %r" % ( input, ) #prints data received
self.request.send("Received: %r" % ( input, ) ) #sends message to client saying..
server= SocketServer.TCPServer( ("",7000), EchoHandler )#adds listener at port 7000
print "Starting Server..."
server.serve_forever() #enables the server to run forever as long as a client is connected
Simple enough, right?
Step 2 Client Application
Now we will code the application which will enable us to send messages to the server.
class Client( object ): #defines client class
rbufsize= -1 #sets read buffer
wbufsize= 0 #sets write buffer
def __init__( self, address=('localhost',7000) ): #defines initialisation function
self.server=socket.socket( socket.AF_INET, socket.SOCK_STREAM )#initiates socket by passing address and protocol parameters
self.server.connect( address ) # connects to set address and port
self.rfile = self.server.makefile('rb', self.rbufsize) #makes file object for response processing
self.wfile = self.server.makefile('wb', self.wbufsize) # same as above but for writing/response sending
def makeRequest( self, text ): # request function which will handle the data transfer
self.wfile.write( text )
self.server.close() # closes this instance of the connection
print "Connecting to Echo Server"
i = 0 #from here to end of file, infinite loop for message sending to server
while (i > -1):
response = c.makeRequest(raw_input("Enter something: "))
And that's it.
Fire up the "Server" app first, then launch the client and try sending some data.
If all goes well, you should get the server to print out some received data. Hope you enjoy making these apps!