Socket Programming in python

Yugam sachdeva
TEK Society
Published in
4 min readOct 19, 2020

Introduction

Socket is an intermediate source of communication between two programs. It is one endpoint of two way communication, which means the socket is sitting at one endpoint and it is able to do both the process i.e. send and receive the data, so socket should be created at both the end for exchanging the data.

source: realpython.com

Socket server runs on a specific system which has a unique IP address(Host) and also that socket is bound to a unique number(Port) so that clients can identify where data should be sent.
Client socket also needs to identify itself to the server that’s why it also uses a local port number.

Note: Use a high digit port number atleast of four digits because most of the small port numbers are already reserved.

Features

  • It is easy to set up a server as well as clients with the help of socket.
  • It is very easy to use socket functions.
  • You can name a socket according to your choice and can communicate on any domain with that name.
  • A client socket is able to communicate to the server as long as it is set up on an open link.
  • You can create sockets in pairs but only for sockets in the AF_UNIX address domain.
  • There is a SOCK_STREAM(TCP) type of socket available which provides you with the acknowledgement service in transferring packets and delivers complete data successfully.

Functions

Socket(): This function is used to create the socket and takes two argument first is family or domain like AF_INET(ipv4) or INET6(ipv6) and second defines the type of socket like SOCK_STRAM(TCP).

bind(): This function is used to bind your socket with a specific host and port which will be passed as an argument to this function and that means your socket will be sitting at a specific location where the client socket can send its data.

listen(): Your socket is ready but will not listen to any client so this function is used to enable your server socket to listen to clients and you can pass a number as an argument to set the limit of clients otherwise it will be able to listen n number of clients.

accept(): This function is used to accept the request by the client to get connected to the server and return two variables that consists of client socket detail and their address.

connect(): This function is used at client side to get connected to the server socket and it also takes two arguments to the host and port to which you want to get connected and before using this function you also need to create a socket at client side too.

send(): This function is used to send data, but you should know one thing before sending the data and that is the data travel on the internet in bit format so you need to encode your data before sending. You can use “UTF-8” format for it.

recv(): This function is used to receive the data from the sender, which means if one program has sent some data it will not be delivered to another end until it will be received. So you need to receive data to get delivered. And don’t forget to decode before using that request.

close(): This function is used to end or shutdown the socket. It is used when you want to destroy your socket.

source: realpython.com

Example

Server

import socketserver = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST='127.0.0.1'
PORT=5000
server.bind((HOST,PORT))
server.listen(1)
print("socket is waiting for client......")
connection,address=server.accept()
print(address," got connected.")
msg="Welcome"
msg=msg.encode('utf-8')
connection.send(msg)
while True:
request=connection.recv(1024)
request=request.decode('utf-8')
print(request)

Explanation

In the first line we are importing the socket module, now we are creating the server socket with the help of ‘socket()’ function. After socket creation we are binding that socket to the localhost and a 5000 port number. Now we are enabling our server to listen for one client then we are waiting for the client to get connected. Whenever a client gets connected, the server will send a welcome msg to the client which is encoded in ‘UTF-8’ format. And in the last, we entered in a loop which is continuously running and receiving messages from the client.

Client

import socketclient=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST='127.0.0.1'
PORT=5000
client.connect((HOST,PORT))
msg=client.recv(1024)
msg=msg.decode('utf-8')
print(msg)
while True:
msg=input("Enter your message:")
msg=msg.encode("utf-8")
client.send(msg)

Explanation

Same for the client, we will create a socket for the client and then try to connect our client to the socket with the help of host and port. Once the client gets connected, we will receive our welcome message and decode it before printing, then we enter in a loop which is taking input and sending that input to the server continuously with decoding it in “UTF-8” format.

Output:

Feel free to reach out to me anytime if you want to discuss something.
I would be more than happy if you send your feedback, suggestions.

also do follow our publication for more such content:

--

--