SoFunction
Updated on 2024-10-30

Explaining the fundamentals of network programming in python in detail

I. What is Network Programming

Network programming involves some basic knowledge of computers, but also with your computer system, mac os/Linux and windows is different, because I use windows, so all the following are windows operating system is applicable, and inside the character encoding windows and mac os is also different, here we realize just a simple What the server sends, the client receives, after that there will be a simulation of ssh remote command and sticky packet problem, and finally can also realize the file download.

Network programming also involves an important part of theoretical knowledge, including what is the network and the more important five-layer protocols, to my understanding, these things are specialized to tell you, in your computer, assuming that you want to receive some of the files, these things are how to transfer over, your computer is how to receive, so here is nothing more than your computer that is the client and the transmission of files on the one hand that is the service point for a Interaction, these I suggest you go to listen to (I feel to personal ability to speak these will be a little level of insufficient) but the big aspects are inseparable from a kind of interaction.

II.socket

As we all know, a large part of the power of python lies in its powerful third-party external library, socket library, also known as sockets, professional interpretation is that the application program is usually through the "socket" to the network to send a request or answer the network request, so that between hosts or between processes on a computer can communicate, and through the sockets of this library you can realize what I said in the front of the The socket library enables the client-server interaction that I described earlier.

basic grammar

socket(family,type,[protocol])

There are three types of family

socket.AF_UNIX Can only be used for inter-process communication on a single Unix system

socket.AF_INET Network communication between servers

socket.AF_INET6 IPv6

There are also three types

socket.SOCK_STREAM Streaming socket , select this parameter when using TCP.

socket.SOCK_DGRAMDatagram socket , select this parameter when using UDP.

socket.SOCK_RAW Raw sockets, ordinary sockets can't handle network packets such as ICMP, IGMP, andSOCK_RAWcan; secondly, SOCK_RAW can also handle special IPv4 messages; furthermore, utilizing raw sockets, IP headers can be constructed by the user via the IP_HDRINCL socket option.

The protocol specifies the type of protocol to be received, usually 0 or not filled in, basically it's not written

2. Some functions related to socket

server-side function

addressGenerally refers to the ip address on your computer, i.e., you open the Windows command prompt, you networked after entering the ipconfig command, inside the IPV4

(address)Bind the socket to an address, i.e., in the client, you have to bind your program to an ip and a port in order to interact with it.

(backlog)The maximum number of connections the operating system can hang. That is, the maximum number of clients your server can pass data to

()Accepts a TCP connection and returns (conn,address), where conn is a new socket object that can be used to receive and send data. address is the address of the connecting client.

Client Functions

(address)Connect to the socket at clientaddress

(bufsize)Accepts data from a TCP socket. The data is returned as a string and bufsize specifies the maximum amount of data to be received.

public function

(string)

Send TCP data. Sends the data in string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of string.

(string)

Send TCP data in full. Sends the data in string to the connected socket, but tries to send all the data before returning. Success returns None, failure throws an exception.

(bufsize)

Accepts data from a UDP socket. Similar to recv(), but the return value is (data,address). Where data is the string containing the received data and address is the address of the socket to which the data was sent.

(string,address)

Send UDP data. Sends data to the socket. address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent.

()

Close the socket.

III. Program requirements

Since it is to realize a kind of interaction, then the life of calling and receiving phone calls can also be understood as a kind of interaction, calling can be understood as sending data, receiving phone calls can be understood as receiving data, so that there is a server and a client, and here we take such a scene to realize the interaction.

Server-side analysis

If you want to send data first you have to have a cell phone and then introduce a socket for interaction, and then you have to carry out a series of binding operations that you need the above function to achieve, first of all, you simulate a cell phone on the client side after the introduction of the socket, you need to bind, turn on the phone, wait for the phone link, send and receive messages, hang up the phone, and other functions

Attention:

1. In the process of binding operation, you need to be connected to the Internet after entering your local ip address, that is, you open the command prompt you enter ipconifg command IPV4 address

2. In the binding of your address will be added after a port number, the port number is arbitrary, but sometimes occupied, occupied then change the following is good

3. There is also an upper function in the manipulation message, which sends the data sent by the client in uppercase to the client.

4. On the client side with accept is to accept the TCP connection and return (conn, address)

--------------------------------server-side----------------------
import socket
#1. Buying a cell phone
phone = (socket.AF_INET,socket.SOCK_STREAM)
# print(phone) # Test your cell phone
 
#2. Insert the card. Bind the cell phone card.
(("192.168.2.18",3234))
 
#3. Power on.
(5)   #5 represents the maximum number of pending connections
 
#4. Wait for the phone link
print("starting")
conn,client_add = ()
 
# 5. Send and receive messages
data=(1024)         #1024 represents the maximum number of received data in bits
print("Client data",data)
 
(())
 
#6. Hang up the phone.
()
 
#7. Shutdown
()

Client Analytics

After the server-side analysis, the client and server are one-to-one correspondence, in sending and receiving messages here, the client sends a lowercase hello to the server, the server will give the client back to an uppercase HELLO

-------------------------------client (computing)-----------------------------
import socket
#1. Buying a cell phone
phone = (socket.AF_INET,socket.SOCK_STREAM)
# print(phone)
 
#2. Dialing
(("192.168.2.18",3234))
 
#3. Send and receive messages
 
("hells".encode("utf"))
data=(1024)
print(data)
 
 
()

IV. Code Upgrade

Plus communication loops

The above code we can see that our implementation is too simple, we just fixed to let it send and receive messages, how do we make this program between the client and the server loop and send and receive what you want, this is what we add inputs and loops can be

----------------------------server-side------------------------
import socket
 
phone = (socket.AF_INET,socket.SOCK_STREAM)
# print(phone)
(("172.20.10.4",3234))
(5)   print("starting")
conn,client_add = ()
print(client_add)
 
while True:
    data=(1024)        
    print("Client data",data)
 
    (())
 
()
()
----------------------------------client (computing)------------------------
import socket
 
phone = (socket.AF_INET,socket.SOCK_STREAM)
# print(phone)
(("172.20.10.4",3234))
 
while True:
    msg = input(">>>:").strip()
    (("utf-8"))
    data=(1024)
    print(data)
 
()

As you can see, we just added the loop input function inside the client side how to add the loop in the server side, so that a kind of circular input can be realized

Plus connecting loops as well as refining

Our above program is a client corresponding to a server, but the real server should be able to correspond to more than one client to send and receive data. We mainly modify the server-side code, the client code should not change much, except that the client should be added to determine whether there is data sent.

1. We did not learn concurrent programming, so our code with a loop to achieve that your server accepts a client's data, you can continue to receive another client's data

2. In addition, we also added a line of code to determine whether your port is occupied so that you can reduce errors

3. I added a client after we will have another problem is whether we need another client to transmit data or our multiple clients in the end there are no data sent, so we need a try and except first to determine the first

--------------------------------server-side-----------------------
import socket
 
phone = (socket.AF_INET,socket.SOCK_STREAM)
(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  # Determine if an interface is occupied
(("172.20.10.4",3234))
(5)   
print("starting")
while True:       # Didn't learn concurrent programming There's no way to execute code and then return to this to continue execution, so use a loop to solve it
    conn,client_add = ()
    print(client_add)
    while True:
        try:
            data=(1024)         
            if not data:break         
            print("Client data",data)
            (())
        except ConnectionResetError :
            break
            ()
()
-----------------client (computing)1-----------------
import socket
 
phone = (socket.AF_INET,socket.SOCK_STREAM)
(("172.20.10.4",3234))
 
while True:
    msg = input(">>>:").strip()
    if not msg: continue          # If the input is empty, the loop continues
    (("utf-8"))
    # print("if send none")
    data=(1024)
    print(data)
    # print(("utf-8"))
 
()
-----------------------------client (computing)2---------------------
import socket
 
phone = (socket.AF_INET,socket.SOCK_STREAM)
(("172.20.10.4",3234))
 
while True:
    msg = input(">>>:").strip()
    if not msg: continue          # If the input is empty, the loop continues
    (("utf-8"))
    # print("if send none")
    data=(1024)
    print(data)
    # print(("utf-8"))
 
()

summarize

That's all for this post, I hope it was helpful and I hope you'll check back for more from me!