SoFunction
Updated on 2024-10-30

Python network communication of the TCP protocol to implement the server and client examples

Preface:

In the last installment we had a preliminary study to understand the concept of network communication (Introduction to Network Programming for Networks and Communications), then in this installment we'll move on to learning about transferring information between servers and clients through network programming.

Socket Programming

1. Introduction

socket programming a protocol-independent network programming interface, the application program can send or receive data through it, it can be opened, read and write and close operations like files.

Socket is an intermediate software abstraction layer for the application layer to communicate with the TCP/IP protocol family, it is a set of interfaces. In the design pattern, Socket is actually a facade pattern, which hides the complex TCP/IP protocol family behind the Socket interface. For the user, a simple set of interfaces is all that is needed to allow Socket to organize the data to conform to the specified protocol.

2. sockets in Python

In Python there has been a socket encapsulated module, when we want to go through Python to realize the socket programming, just need to import the module on the line, and then in accordance with the methods inside you can go to build a LAN server and the user side.

import module

import socket

Server implementation

Every time we send a message on WeChat, QQ, we send the information will be passed through the LAN and then passed to the public network, and then into the bound public network server, and then the server through the network protocol down to the receiver. Network communication is probably such a process, then here I go through the tcp protocol to realize the LAN directly to the server code

import random
import socket
#1. Create server object
server=(socket.AF_INET,socket.SOCK_STREAM)
# Parameter 1: socket.AF_INET, denotes ipv4 address
# Parameter 2: socket.SOCK_STREAM denotes tcp protocol encapsulated parameters
#2. Code to get the current computer address
p=(socket.AF_INET,socket.SOCK_DGRAM)
(('8.8.8.8',80))
nowip=()[0]
()
port=8888
print('Current ip address:',nowip)
print('Current port number:',port)
#3. Bind the server to this computer.
((nowip,port))
#4. Set the listening mode and set the maximum number of listeners.
(128) # Set the maximum number of connections 128
print('Server is up, waiting to connect ......')
#5. Waiting for clients to connect
conn, addr = ()
# conn is the socket object to connect to the client
# addr is the address of the client's connection
while 1:
    try:
        #6. Accept data from the client
        #Network data is sent as a stream of bytes.
        data=(1024).decode('utf8') #The parameter 1024 indicates the maximum number of bytes to be accepted at a time. decode is used to decode the byte stream encoded into characters.
        if not data:# When null data is received it means that the client is disconnected
            print(f'{addr}Disconnected.')
            break
        print(f'----{addr}Sent----',data)
        #7. Returns a random number from 0 to 100 to the client.
        (str((0,100)).encode('utf8'))# Perform byte stream encoded sends
    except ConnectionResetError:
        print('error')
        break
#7. Close the socket object
()
#8. Shutting down the server
()

User Side Implementation

Client code implementation is also similar to the server, the realization of the first to create a client object, and then connect to the server's address and port number, and then you can go to the realization of the server to send and receive information. The code is as follows:

# Client
import socket
#1. Create client objects
client=(socket.AF_INET,socket.SOCK_STREAM)
#2. Connect to the server address and port
(('10.33.110.204',8888))
count=1 # Counting
while 1:
    a=input(r'Enter what you want to send(\qabort):').strip()
    if a==r'\q':
        break
    if not a: # Re-enter when the data sent is empty
        print('The data sent cannot be empty')
        continue
    #3. Send the data to the server
    (('utf8'))
    #4. Get the data sent by the server.
    data = (1024)  # receive
    if not data:
        break
    print(f'Messages sent by the other party--{count}--:',("utf8"))
    count+=1
#5. Close the client
()
 

(Note: the above code function is in the local area network to realize the server and the client to send and receive information between, if two devices connected to different WiFi then it can not send information)

to this article on Python network communications TCP protocol to achieve server and client examples of the article is introduced to this, more related PythonTCP protocol to achieve server and client content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!