Python Server
The server-side is a machine on which all the operations are executed as requested by the client-side, we will perform addition, subtraction, multiplication, and division operation on the server. To do so the server received input from a client and performs the basic operation by itself. when the result is ready Python server then sends the output to the client machine.
Python3
# Import socket module import socket # Here we use localhost ip address # and port number LOCALHOST = "127.0.0.1" PORT = 8080 # calling server socket method server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((LOCALHOST, PORT)) server.listen( 1 ) print ( "Server started" ) print ( "Waiting for client request.." ) # Here server socket is ready for # get input from the user clientConnection, clientAddress = server.accept() print ( "Connected client :" , clientAddress) msg = '' # Running infinite loop while True : data = clientConnection.recv( 1024 ) msg = data.decode() if msg = = 'Over' : print ( "Connection is Over" ) break print ( "Equation is received" ) result = 0 operation_list = msg.split() oprnd1 = operation_list[ 0 ] operation = operation_list[ 1 ] oprnd2 = operation_list[ 2 ] # here we change str to int conversion num1 = int (oprnd1) num2 = int (oprnd2) # Here we are perform basic arithmetic operation if operation = = "+" : result = num1 + num2 elif operation = = "-" : result = num1 - num2 elif operation = = "/" : result = num1 / num2 elif operation = = "*" : result = num1 * num2 print ( "Send the result to client" ) # Here we change int to string and # after encode send the output to client output = str (result) clientConnection.send(output.encode()) clientConnection.close() |
Output:
Simple Calculator in Python Socket Programming
In this article, we are going to know how to make a simple calculator in Python socket programming.
Prerequisite: Socket Programming in Python.
First, we will understand the basics of Python socket programming. Socket programming is used to set up a communication channel between two nodes on a network. It provides Inter connected communication (IPC). The network can be a logical, local network and physical network to connect external network. In this example, we will write local socket programming code in Python.
Contact Us