Socket Programming in Python
Sockets and the socket API are used to send messages across a network. They provide a form of inter process communication. The network can be a logical, local network to the computer, or one that’s physically connected to an external network, with its own connections to other networks.
Echo Server
#!/usr/bin/env python3 import socket HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) # associating with specific network interface and port number s.listen() # listening for incoming connections conn, addr = s.accept() # accepting the connections with conn: print('Connected by', addr) while True: data = conn.recv(1024) # recieve data upto 1024 bytes, then it will block if not data: break conn.sendall(data) #
data send by the client is echoed back
Echo client
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world') # data send by the client
data = s.recv(1024)
print('Received', repr(data))
Open a terminal window and navigate to the folder containing the scripts.
The terminal will appear to hang as we there is no connections active now only the server is running
Now, run the echo-client script in another terminal,
Now in the echo-server window,
SO THIS IS SINGLE SERVER AND CLIENT SCRIPT
Comments
Post a Comment