You are here
Home > HelloWorld >

Python Socket Programming – Server, Client Example

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.


  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.


bind()=binds address to socket.

listen()=sets up and start tcp server.

connect()=initiates tcp server connection.

gethostname()=return hostname.

import socket

def server_program():

host = socket.gethostname()
port = 5000  
server_socket = socket.socket() 
server_socket.bind((host, port))  
conn, address = server_socket.accept()  
print("Connection from: " + str(address))
while True:
data = conn.recv(1024).decode()
if not data:
print("from connected user: " + str(data))
data = input(' -> ')

if name == ‘main‘:

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':
data = client_socket.recv(1024).decode()  
print('Received from server: ' + data)  
message = input(" -> ")  

if name == ‘main‘:


Leave a Reply

%d bloggers like this: