Python Socket Programming – Server, Client Example HelloWorld by mayuri takle - February 26, 2019April 11, 20190 Contents Socket is the endpoint of a bidirectional communications channel between server and client. Sockets may communicate within a process, between processes on the same machine, or between processes on different machines. For any communication with a remote program, we have to connect through a socket port. steps: Python socket server program executes at first and wait for any requestPython socket client program will initiate the conversation at first.Then server program will response accordingly to client requests.Client program will terminate if user enters “bye” message. Server program will also terminate when client program terminates, this is optional and we can keep server program running indefinitely or terminate with some specific command in client request. We can obtain host address by using socket.gethostname() function. It is recommended to user port address above 1024 because port number lesser than 1024 are reserved for standard internet protocol. fuctions: bind()=binds address to socket. listen()=sets up and start tcp server. connect()=initiates tcp server connection. gethostname()=return hostname. server.py import socket def server_program(): host = socket.gethostname() port = 5000 server_socket = socket.socket() server_socket.bind((host, port)) server_socket.listen(2) conn, address = server_socket.accept() print("Connection from: " + str(address)) while True: data = conn.recv(1024).decode() if not data: break print("from connected user: " + str(data)) data = input(' -> ') conn.send(data.encode()) conn.close() if name == ‘main‘: server_program() client.py import socket def client_program(): host = socket.gethostname() port = 5000 client_socket = socket.socket() client_socket.connect((host, port)) message = input(" -> ") while message.lower().strip() != 'bye': client_socket.send(message.encode()) data = client_socket.recv(1024).decode() print('Received from server: ' + data) message = input(" -> ") client_socket.close() if name == ‘main‘: client_program() output: Share this:Click to share on Twitter (Opens in new window)Click to share on Facebook (Opens in new window)MoreClick to share on LinkedIn (Opens in new window)Click to share on WhatsApp (Opens in new window)Click to email a link to a friend (Opens in new window)Like this:Like Loading... Related