DEV Community

Idris Jimoh
Idris Jimoh

Posted on

2 2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs