You are here
Home > HelloWorld >

Python Socket Programming – Server, Client Example

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:

  1. Python socket server program executes at first and wait for any request
  2. Python socket client program will initiate the conversation at first.
  3. Then server program will response accordingly to client requests.
  4. 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:

Leave a Reply

Top