Here the communication is between a client and server. This can be regarded as a simple chat program exchanging small texts. The protocol used is IP.
This program is written in Python.
server.py:
import socket # server host address, denotes localhost if empty string. HOST = ''; # port which is used to communicate server and client programs PORT = 40005; with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sc: sc.bind((HOST, PORT)); sc.listen(1); connection, address = sc.accept() with connection: print('Connected by client host: %s' % repr(address)) while True: data = connection.recv(1024) if not data: break; # printing client message here. print("Received from client: %s" % repr(data)) data_to_send = input("Enter message to client:") if not data_to_send: break; # sending message as bytes to client. connection.sendall(bytearray(data_to_send, 'utf-8'))
client.py:
# Chatting client program import socket # host address where client program is running. HOST = ''; # port on which server and client programs are communicating. PORT = 40005; with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sc: sc.connect((HOST, PORT)) while True: data_to_send = input("Enter message to server: ") if not data_to_send: break; # sending message as bytes to server. sc.sendall(bytearray(data_to_send, 'utf-8')) data = sc.recv(1024); # printing server message. print('Received from server: %s'% repr(data))
Get Answers For Free
Most questions answered within 1 hours.