Python Client / Server

Here we can create simple python client server code for communication

Python Client

import socket

ip_address = '127.0.0.1'
port_number = 1234
cs = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

cs.connect((ip_address,port_number))

msg = input("Enter message to send :")

while msg!='quit':
    cs.send(msg.encode())
    msg = cs.recv(1024).decode()
    print(msg)
    msg = input("Enter message to send :")

cs.close()

Python Server

import socket
import threading,time

ip_address = '127.0.0.1'
port_number = 1234

THREADS = []
CMD_INPUT = []
CMD_OUTPUT = []

def handle_connection(connection,address):
    msg = connection.recv(1024).decode()
    while msg!='quit': 
        print(msg)
        connection.send(msg.encode())
        msg = connection.recv(1024).decode()
    close_connection(connection)


def close__connection(connection):
    connection.close()
ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ss.bind((ip_address,port_number))
ss.listen(5)


while True:    
    connection , address = ss.accept()
    t = threading.Thread(target=handle_connection,args=(connection,address))
    THREADS.append(t)
    t.start()

Last updated

Was this helpful?