Simple Socket Programming in Python

In this Python Socket Programming article we want to learn about Simple Socket Programming in Python, Socket programming is powerful tool for creating networked applications, and it allows to communicate with each other across network. there are different builtin support for socket programming, and this makes it easy to get started with network programming. in this article we want to talk about the basics of socket programming and show you how to create simple client server application.

 

 

First of all for creating client server application is to create a socket. socket is a software object that connects two processes together. in Python you can create a socket using the socket module.

 

 

Next step is to bind the socket to specific address and port number. this is done using the bind() method.

 

After that the socket is bounded, and we can start listening for incoming connections using  listen() method, in this example we are only allowing one client to connect at a time.

 

When a client tries to connect to the server, server will receive a notification. accept() method is used to accept incoming connections.

 

 

Once client and server is connected, they can start sending and receiving data. we can use send() and recv() methods send and receive data over the network.

 

After communication is completed, we need to close the connection between client and server using close() method.

 

 

So this is the complete code for simple client-server application using socket programming.

 

This is our server code

 

 

This is our client code

 

In the server code we have created socket object, and bind it to specific address and port number, listen for incoming connections, accept an incoming connection from client, send data to the client, receive data from the client and then close the connection.

In the client code we have created socket object, connected to the server, receives data from the server, send data to the server and then close the connection. you need to run these two codes in sperate terminals.

 

 

Learn More

Leave a Comment