DEV Community

Idris Jimoh
Idris Jimoh

Posted on

Create a Network Client with Python

Let us write a very simple client program which opens a connection to a given port 12345 and given host. This is very simple to create a socket client using Python's socket module function.

The socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.

The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits.

#!/usr/bin/python           
# This is client.py file

import socket               
# Import socket module

s = socket.socket()         
# Create a socket object
host = socket.gethostname() 
# Get local machine name
port = 12345                
# Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close()                     
# Close the socket when done
Enter fullscreen mode Exit fullscreen mode

Now run the server.py (check my previous post) in background and then run above client.py to see the result.

# Following would start a server in background.
$ python server.py & 

# Once server is started run client as follows:
$ python client.py

Enter fullscreen mode Exit fullscreen mode

This would produce following result.

Got connection from ('127.0.0.1', 48437)
Thank you for connecting
Enter fullscreen mode Exit fullscreen mode

Top comments (0)