Python Advanced Programming Lecture 5: Socket Programming-udp

1. IP address

Purpose: Used to mark a computer on the network

1.1 Windows and Linux view network card information

  • 1 Linux中 ifconfig
  • 2 windows中 ipconfig

1.2 Classification of IP addresses

ip v4
ip v6

Classification of ip address

2. Port

The port is a running id assigned to each program in the computer to identify the program
port

2.1 Classification of ports

  • 1. Well known ports
    such as:

Port 80 is allocated to HTTP service
Port 21 is allocated to FTP service The
range is from 0 to 1023

  • 2. Dynamic port

The range of dynamic port is from 1024-65535

3. TCP/IP protocol

The TCP/IP protocol is the abbreviation of Transmission Control Protocol/Internet Protocol, that is, Transmission Control Protocol/Internet Protocol
, also known as Network Communication Protocol. It is the most basic protocol of the Internet and the foundation of the Internet International Internet. It consists of the IP protocol and The TCP protocol composition of the transport layer.
TCP/IP defines how electronic devices connect to the Internet and how data is transmitted between them. The protocol uses a 4-layer
hierarchical structure, and each layer calls the protocol provided by its next layer to complete its own needs.

3.1 TCP/IP components

The TCP/IP network model four-layer model is fundamentally the same as the OSI seven-layer network model, except that several layers are combined
TCP/IP components

3.2 Example diagram of TCP/IP data transmission

Transmission example diagram

3.3 Two transport protocols of TCP/IP transport layer

  • UDP
    udp

  • TCP
    TCP

The difference between TCP and UDP:

1. TCP is connection-oriented; UDP is connectionless, that is, there is no need to establish a connection before sending data.
2. TCP provides reliable services. That is to say, the data transmitted through the TCP connection has no errors, no loss, no duplication, and arrives in order; UDP does its best to deliver, that is, it does not guarantee reliable delivery.
3. UDP has better real-time performance and is more efficient than TCP High, suitable for high-speed transmission and real-time communication or broadcast communication.
4. Each TCP connection can only be point-to-point; UDP supports one-to-one, one-to-many, many-to-one and many-to-many interactive communications.
5. TCP requires more system resources, while UDP requires more system resources. less.

4. socket

Socket is also called "socket". Applications usually send requests to the network or respond to network requests through "sockets", so that hosts or processes on a computer can communicate. In the vernacular, a socket is a "phone" installed in each home by two nodes in order to communicate with each other.

4.1 Use of socket

1. Create a socket
2. Use the socket to receive/send data
3. Close the socket

4.2 udp sending program

import socket
def main():
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udp_socket.sendto(b'nihao',('127.0.0.1',8080))
    udp_socket.close()
if __name__ == '__main__':
    main()

The parameter description in the above example:
socket.socket (protocol family, socket type)

  • The protocol family means which ip version type is used:
    1.AF_INET means IPv4 version
    2.AF_INET6 means IPv6 version
  • Which protocol TCP/UDP protocol is used by the socket type:
    1. SOCK_DGRAM means UDP
    2. SOCK_STREAM means TCP is the default
  • udp_socket.sendto(b'nihao',('192.168.0.162',8080))
    1 b'nihao' represents data: bytes
    2 ('192.168.0.162',8080) represents: address: Union[tuple, str))
    is the parameter in the sendto() method

data:bytes If we are not passing a string directly, but passing it through a parameter, we need to convert the data type first, and the conversion method:
data ='hello'
data = data.encode()
is in windows Since the default number is GBK, and the encode in python is UTF-8 by default, if we do not change the character set, it will cause us to receive Chinese character data garbled, so we also need to pass in the specified character set
data = data.encode(encoding ='GBK')
address: Union[tuple, str] To pass parameters in the above tuple format ,
finally close the object

4.3 udp receiving program

  • Steps to receive data:

1 Create a socket
2 Bind local information (IP and port)
3 Receive data
4 Print data
5 Close the socket
Example of receiving program:

import socket
def main():
    udp_recv = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udp_recv.bind(('',7890))
    recv_data = udp_recv.recvfrom(1024)
    # print(recv_data)
    host_info = str(recv_data[1])
    message = recv_data[0].decode('gbk')
    print(host_info,message)
if __name__ == '__main__':
    main()   

4.4 Port binding problem

If the program is running without a port bound, the operating system will automatically assign a port to the program. And the same port cannot be used twice.
In other words, when sending, the program will automatically assign a dynamic port when the sender's port is not bound.

4.5 UDP simple chat

Features:

1. Create a socket. Socket can send and receive data at the same time
2. Send data
3. Receive data

import socket

#定义发送的程序
def udp_send(udp_socket):
    send_data = input("请输入您要发送的信息:")
    send_host = input('请输入要发送的ip地址:')
    send_port = int(input("请输入您要选择发送的端口"))
    udp_socket.sendto(send_data.encode('gbk'),(send_host,send_port))
    

#定义接收的程序
def udp_recv(udp_socket):
    recv_data =  udp_socket.recvfrom(1024)
    print("{}{}".format(str(recv_data[1]),recv_data[0].decode('gbk')))


def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind(("",7790))
    while True:
        udp_send(udp_socket)
        udp_recv(udp_socket)
    udp_socket.close()

if __name__ == '__main__':
    main()

Guess you like

Origin blog.csdn.net/scyllake/article/details/97291549