DEV Community


Create a Network Client with Python

The Rebel NeXtdoor | Python Developer | Developer Advocate | Ehub247, TechO’clock and iDer Ambassador | Technical Writer
・1 min read

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.

# This is 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)
# Close the socket when done
Enter fullscreen mode Exit fullscreen mode

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

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

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

Enter fullscreen mode Exit fullscreen mode

This would produce following result.

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

Discussion (0)