[Python] fundamentals of network programming

Time:2022-3-25

Client / server network programming

Before the server responds to the client request, some preliminary setting processes must be carried out to prepare for the future work. First, a communication endpoint will be created, which enables the server to listen for requests. Once a communication endpoint has been established, the listening server can enter an infinite loop, waiting for clients to connect and respond to their requests.

All the client needs to do is create its single communication endpoint and then establish a connection to the server. The client can then issue a request that includes any necessary data exchange. Once the request is processed by the server and the client receives the result or some confirmation information, the communication will be terminated.

Sockets: communication endpoints

A socket is a computer network data structure. Before any type of communication begins, a network application must first create a socket.

Generally speaking, a socket is an internal endpoint built to send and receive data. A single network will have two sockets, one for each communication device or program. These sockets are a combination of IP addresses and ports. A single device can have n slots depending on the port number used. Different ports can be used for different types of protocols.

Network programming in Python

To implement socket programming using python, you need to importsocketModule or framework. This module consists of the built-in methods needed to create sockets and help them correlate with each other.

Some important methods are as follows:

Methods describe
socket.socket() Used to create sockets (both server and client need to create sockets)
socket.accept() Used to accept connections. It returns a pair of values (Conn, address), where conn is the new socket object used to send or receive data, and address is the address of the socket existing at the other end of the connection
socket.bind() Used to bind to the address specified as a parameter
socket.close() Used to mark a socket as closed
socket.connect() Used to connect to a remote address specified as a parameter
socket.listen() Enables the server to accept connections

TCP client / server

Server

#! /usr/bin/env python

from socket import *

HOST = '' 	// Mark the bind method to indicate that any available address can be used
PORT = 39543
BUFSIZE = 1024 	// Buffer size
ADDR = (HOST,PORT)

sersock = socket(AF_INET,SOCK_STREAM) 	// Create server socket
sersock. bind(ADDR) 	// Socket and address binding
sersock. listen(5) 	// Listening Connections 

while True:
    print('waiting for connection ---')
    clisock,addr = sersock. accept() 	// Accept client connections
    print('--- connected from :',addr)
    
    while True:
        data = clisock. recv(BUFSIZE). decode() 	// Conversation reception
        if not data:
            break
        clisock. Send (data. Encode()) // send conversation
    clisock.close()
sersock. close 	// Close the server socket

client

#! /usr/bin/env python

from socket import *

HOST = 'localhost'
PORT = 39543
BUFSIZE = 1024
ADDR = (HOST,PORT)

clisock = socket(AF_INET,SOCK_STREAM)
clisock.connect(ADDR)

while True:
    data = input('>')
    if not data:
        break
    clisock.send(data.encode())
    data = clisock.recv(BUFSIZE).decode()
    if not data:
        break
    print(data)
clisock.close()

Execution effect:

client:

>aaa
aaa

Server:

waiting for connection ---
--- connected from : ('127.0.0.1', 8370)

Next, we will transform this basic demo program into a simple chat tool:

Half duplex chat

Server

#! /usr/bin/env python

from socket import *

HOST = ''
PORT = 39543
BUFSIZE = 1024
ADDR = (HOST,PORT)

sersock = socket(AF_INET,SOCK_STREAM)
sersock.bind(ADDR)
sersock.listen(5)

print('waiting for connection ---')
clisock, addr = sersock.accept()
print('--- connected from :', addr)
while True:
    data = clisock.recv(BUFSIZE).decode()
    print('>' + data)
    resp = input('+')
    resp = '+'+resp
    if not resp:
        break
    clisock.send(resp.encode())
clisock.close()
sersock.close()

client

#! /usr/bin/env python

from socket import *

HOST = 'localhost'
PORT = 39543
BUFSIZE = 1024
ADDR = (HOST,PORT)

clisock = socket(AF_INET,SOCK_STREAM)
clisock.connect(ADDR)

while True:
    data = input('>')
    if not data:
        break
    clisock.send(data.encode())
    data = clisock.recv(BUFSIZE).decode()
    if not data:
        break
    print(data)
clisock.close()

So you can chat happily