What is the Network?

A network is a tool that helps two or more parties to connect together and then transfer data.

It’s about connecting multiple parties and communicating with each other, that is, passing data from one party to the other, and in order for software running on different computers to be able to pass data to each other, you need to use the capabilities of the network.

IP address: used to mark a computer on the network, such as 192.168.1.1, which is unique on the local LAN.


How do processes on different computers communicate with each other?

The first problem to solve is how to uniquely identify a process, otherwise communication is impossible!

On a computer, a process can be uniquely identified by a process id PID, but this is not possible on a network.

In fact, the TCP/IP protocol family has helped us to solve this problem, the IP address of the network layer can uniquely identify the host in the network

The transport layer protocol + port can uniquely identify the application process (process) in the host.

In this way, the process of the network can be identified by IP address, protocol and port, and the process communication in the network can use this symbol to interact with other processes.


What is a Socket?

A Socket is a form of communication between processes. It is different from other processes in the following major ways:

It can realize the interprocess communication between different hosts. Most of our various services on the network are based on Socket to complete the communication

For example, we browse the web, chat on QQ, send and receive emails and so on every day.


The socket () function

Now that we know about networks, how do we do network programming in Python? In Python, we use the socket() function in the socket module to create a socket. The syntax is as follows:

import socket
socket.socket(family, type, proto)
Copy the code

Parameters:

  • family:The socket family can beAF_UNIX(communication between processes of the same machine) orAF_INET(Internet interprocess communication)
  • type:Socket types can be classified according to whether they are connection-oriented or non-connection-orientedSOCK_STREAMFlow socket, mainly used forTCP protocol) orSOCK_DGRAMDatagram socket, mainly used forUDP protocol.)
  • Protocol: The default value is 0


Creating a Socket

The socket usage flow is similar to the file usage flow

  • Create a socket

  • Use sockets to receive/send data

  • Close the socket


TCP Socket

import scoket

Create a TCP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Use of socket function
# here omitted...

s.close()
Copy the code


UDP Socket

import scoket

Create a UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Use of socket function
# here omitted...

s.close()
Copy the code


Socket Socket object method

methods describe
Server side socket
socket.bind() Bind the address (host,port) to the socket inAF_INETBelow, address is represented as a tuple (host,port).
socket.listen() The TCP listening starts. Procedure Backlog specifies the maximum number of connections that the operating system can suspend before rejecting them. This value should be at least 1, and 5 will do for most applications.
socket.accept() Passively accept a TCP client connection and (blocking) wait for the connection to arrive
Client socket
socket.connect() Initializes the TCP server connection. Generally, the format of address is a tuple (hostname, port). If the connection fails, socket.error is returned.
socket.connect_ex() An extended version of the connect() function that returns an error code instead of throwing an exception
Socket functions for public use
socket.recv() Receives TCP data, which is returned as a string. Bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
socket.send() Send TCP data, sending the data in string to the connected socket. The return value is the number of bytes to send, which may be smaller than the size of the string.
socket.sendall() Send TCP data intact. Send TCP data intact. Sends the data in the string to the connected socket, but attempts to send all the data before returning. Returns None on success and raises an exception on failure.
socket.recvfrom() Receives UDP data, similar to recv(), but returns (data,address). Where data is the string containing the received data and address is the socket address that sends the data.
socket.sendto() Sends UDP data to a socket. Address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent.
socket.close() Close the socket
socket.getpeername() Returns the remote address of the connected socket. The return value is usually a tuple (ipaddr,port).
socket.getsockname() Returns the socket’s own address. Usually a tuple (ipaddr,port)
socket.setsockopt(level,optname,value) Sets the value of the given socket option.
socket.getsockopt(level,optname[.buflen]) Returns the value of the socket option.
socket.settimeout(timeout) Sets the timeout period for socket operations. Timeout is a floating point number in seconds. A value of None indicates that there are no expired periods. In general, super periods should be set when sockets are first created, because they may be used for connected operations (such as connect())
socket.gettimeout() Returns the value of the current timeout period, in seconds, or None if no timeout period is set.
socket.fileno() Returns the file descriptor for the socket.
socket.setblocking(flag) If flag is False, the socket is set to non-blocking mode, otherwise the socket is set to blocking mode (default). In non-blocking mode, if recv() does not find any data, or send() does not send data immediately, socket.error is raised.
socket.makefile() Creates a file associated with the socket


Socket object methods, with the exception of makefile(), correspond to socket-specific Unix system calls.

Can go to https://docs.python.org/zh-cn/3/library/socket.html?highlight=socket#socket-objects Python official document for more details.


The Socket small case

UDP chat device

import socket


def send_msg(udp_socket) :
    """ Get keyboard data and send it to the other party. """
    # 1. Input data from the keyboard
    msg = input("\n Please enter the data to send :")
    # 2. Enter the IP address of the other party
    dest_ip = input("\n Please enter the IP address of the other party :")
    # 3. Enter the other party's port
    dest_port = int(input("\n Please enter the other party's port:"))
    # 4. Send data
    udp_socket.sendto(msg.encode("utf-8"), (dest_ip, dest_port))


def recv_msg(udp_socket) :
    """ Receive data and display """
    # 1. Receive data
    recv_msg = udp_socket.recvfrom(1024)
    # 2. Decoding
    recv_ip = recv_msg[1]
    recv_msg = recv_msg[0].decode("utf-8")
    # 3. Display the received data
    print(">>>%s:%s" % (str(recv_ip), recv_msg))


def main() :
    # 1. Create a socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 2. Bind local information
    udp_socket.bind(("localhost".7890))
    while True:
        # 3. Select features
        print("="*30)
        print("1: Send message")
        print("2: Receiving messages")
        print("="*30)
        op_num = input("Please enter the number of the function to operate :")

        # 4. Call the corresponding function based on the selection
        if op_num == "1":
            send_msg(udp_socket)
        elif op_num == "2":
            recv_msg(udp_socket)
        else:
            print("Incorrect input, please re-enter...")


if __name__ == "__main__":
    main()
Copy the code

The running results are as follows:

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =1: Sending a message2: Receiving messages ============================== Please enter the number of the function to operate:1Please enter the data to send:123Please enter the IP address of the other party:10.7330.48.Please enter the port of the other party:7890= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =1: Sending a message2: Receiving messages ============================== Please enter the number of the function to operate:2> > > ('10.73.30.48'.7890) :123= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =1: Sending a message2: Receives messages ==============================Copy the code


File loader

The server code is as follows:

import sys
from socket import *


def get_file_content(file_name) :
    """ Get the contents of the file """
    try:
        with open(file_name, "rb") as f:
            content = f.read()
        return content
    except:
        print("Files not downloaded :%s" % file_name)


def main() :

    if len(sys.argv) ! =2:
        print("Python3 XXX.py 7890")
        return
    else:
        Python3 xxx.py 7890
        port = int(sys.argv[1])


    # to create a socket
    tcp_server_socket = socket(AF_INET, SOCK_STREAM)
    
    The null string represents the lockhost localhost
    address = (' ', port)
    tcp_server_socket.bind(address)
    
    Change an active socket to a passive socket
    tcp_server_socket.listen(128)

    while True:
        # wait for the client link, i.e. send the file for the client
        client_socket, clientAddr = tcp_server_socket.accept()
        
        Receive the data sent by the other party
        recv_data = client_socket.recv(1024)  Receive 1024 bytes
        file_name = recv_data.decode("utf-8")
        print("Requested file name :%s" % file_name)
        file_content = get_file_content(file_name)
        
        Send file data to client
        The data in file_content is already in binary format because the open file is opened in RB mode.
        # Therefore, no encode is required
        if file_content:
            client_socket.send(file_content)
            
        # close this socket
        client_socket.close()

    Close the listening socket
    tcp_server_socket.close()


if __name__ == "__main__":
    main()
Copy the code


The client code is as follows:

from socket import *


def main() :

    # to create a socket
    tcp_client_socket = socket(AF_INET, SOCK_STREAM)

    # Destination information
    server_ip = input("Please enter the server IP address :")
    server_port = int(input("Please enter server port:"))

    # link server
    tcp_client_socket.connect((server_ip, server_port))

    Enter the file name you want to download
    file_name = input("Please enter the file name to download:")

    Send a file download request
    tcp_client_socket.send(file_name.encode("utf-8"))

    Receive data sent by the other party, Max 1024 bytes (1K)
    recv_data = tcp_client_socket.recv(1024)
    # print(recv_data.decode(' utF-8 '))
    Create file if data is received, otherwise not
    if recv_data:
        with open("[received]"+file_name, "wb") as f:
            f.write(recv_data)

    Close the socket
    tcp_client_socket.close()


if __name__ == "__main__":
    main()
Copy the code


  • Python file download server. Py 7890Enabling the Server
  • Python file loader client.pyStart the Client

The operation diagram is as follows:


Python Internet module

Here is a list of some of the protocols that are important modules for Python network programming:

agreement Useful function The port number Python module
HTTP Web access 80 httplib, urllib, xmlrpclib
NNTP Read and post news articles, commonly known as “posts” 119 nntplib
FTP The file transfer 20 ftplib, urllib
SMTP Send E-mail 25 smtplib
POP3 Receive mail 110 poplib
IMAP4 Access to email 143 imaplib
Telnet The command line 23 telnetlib
Gopher Find information 70 gopherlib, urllib


The public,

Create a new folder X

Nature took tens of billions of years to create our real world, while programmers took hundreds of years to create a completely different virtual world. We knock out brick by brick with a keyboard and build everything with our brains. People see 1000 as authority. We defend 1024. We are not keyboard warriors, we are just extraordinary builders of ordinary world.