Python Learning Diary - Day 28 - Introduction to udp

Series Article Directory

  • udp send data

foreword

What I'm learning today is how to use udp to send and receive data

First download and install a tcp/udp network debugging assistant in advance, Baidu can do it, the installation is very convenient, in order to use udp and tcp to receive data later

It contains the ip and port of the receiver, and you can click the hexadecimal tick at the bottom

operate:

import socket

#  Use the same socket to send and receive data
def main():
    #  create a udp socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # Data can be sent and received using sockets
    # udp_socket.sendto("hahah", the IP and port of the other party)
    udp_socket.sendto(b"hahah", ("192.168.2.101", 8080))
    

    # close the socket
    udp_socket.close()

if __name__ == "__main__":
main()

Output result:

The debugger successfully received the message

(Note: The ip address of the network debugging assistant is best adjusted to be the same as the first three sets of data in the IPV4 address of your own computer., otherwise the message will not be received)

Let's focus on the "b" here

 

First of all, after adding a b in Python, it is the bytes type, which is similar to the int and str types that we have learned before.

When we use the sendto command to send data in Python, it must be of bytes type, but writing b is not general enough. There are other methods below.

Let's talk about utf-8 again:

utf-8 is an encoding format that supports global languages, as I have said before

  operate:

#  Use the same socket to send and receive data
def main():
    #  create a udp socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    #  Get data from keyboard
    send_data = input("Please enter the data to send:")

    # Data can be sent and received using sockets
    # udp_socket.sendto("hahah", the IP and port of the other party)
    # udp_socket.sendto(b"hahah", ("192.168.2.101", 8080))
    udp_socket.sendto(send_data.encode("utf-8"), ("192.168.2.101", 8080))

    # close the socket
    udp_socket.close()

if __name__ == "__main__":
    main()

One last exercise:

Application:udp chatter

illustrate:

· Write programs on one computer with 2 functions

  1. Get keyboard data and send it to the other party
  2. receive data and display

・And function data to select the above 2 function calls

Require:

implement the above procedure

First, let's think about it

 (Note: 127.0.0.1 here is the local loopback ip address of each computer. If it is not connected to the Internet, the address is the same, so if you test on your own computer, you can directly enter this ip, but the port is still the same as before. Set the same, the same computer, the port of each process is unique)

Output result:

 

Here you can see that after sending, the program is still running, and no success is displayed, because recvfrom will be blocked when no data arrives. You can end the process by replying to the message in the network debugging assistant.

 

 

Finally, it works:

Code:

import socket


def send_msg(udp_socket):
    """Send a message"""
    # Get what to send
    send_data = input("Please enter the message to send:")
    dest_ip = input("Please enter the counterparty ip: ")
    dest_port = int(input("Please enter the counterparty port: "))
    udp_socket.sendto(send_data.encode("utf-8"), (dest_ip, dest_port))


def recv_msg(udp_socket):
    """Receive data"""
    # Get what to send
    recv_data = udp_socket.recvfrom(1024)
    print("%s:%s" % (str(recv_data[1]), recv_data[0].decode("utf-8")))
def main():
    # create socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # binding information
    udp_socket.bind(("", 7788))

    # loop to process things
    while True:
        print("-----xxx chatter-----")
        print("1:Send a message")
        print("2:receive message")
        print("0:Exit system")
        op = input("Please enter the function:")

        if op == "1":
        # send
            send_msg(udp_socket)
        elif op == "2":
        # receive and display
            recv_msg(udp_socket)
        elif op == "0":
            break
        else:
            print("You entered incorrectly, please try again:")

if __name__ == "__main__":
    main()

console:

Debug assistant:

Note ①:

 

Here is to bind the port we send ourselves, so it is convenient to practice and remember

Note ②:

A loop is added to optimize the system and can be exited at any time

Note ③:

 

The final completed program encapsulates both receiving and sending messages into functions, in order to beautify the code, so that we can view it easily and know the function of this code at a glance. It will not be like the previous practice, all the code is written in the main program, it looks more cumbersome, and the problem is not easy to find

Summarize

The concept and use of tcp network will be updated later

Tags: Python udp network programming language

Posted by shadowwebs on Tue, 08 Nov 2022 03:48:52 +0530