Python implements the multitasking version of UDP chat

Time:2021-10-23

In this article, an example is given to share with you the implementation of the multitasking version of UDP chat in Python for your reference. The specific contents are as follows

1、 Case example

2、 Case description

1. Write a program with 2 threads.
2. Thread 1 is used to receive data and display it.
3. Thread 2 is used to detect keyboard data and then send data through UDP.

3、 Reference code

import socket
import threading


def send_msg(udp_socket):
    "" "get keyboard data and send it to each other" ""
    while True:
        #1. Enter data from the keyboard
        MSG = input ("\ nPlease enter the data to send:")
        #2. Enter the IP address of the other party
        dest_ IP = input ("\ nPlease enter the IP address of the other party:")
        #3. Enter the other party's port
        dest_ Port = int (input ("\ nPlease 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" ""
    while True:
        #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 received data
        print(">>>%s:%s" % (str(recv_ip), recv_msg))


def main():
    #1. Create socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    #2. Bind local information
    udp_socket.bind(("", 7890))

    #3. Create a sub thread to receive data
    t = threading.Thread(target=recv_msg, args=(udp_socket,))
    t.start()
    #4. Let the main thread detect keyboard data and send it
    send_msg(udp_socket)


if __name__ == "__main__":
    main()

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

OC basis

IOS development interview essential skills chart.png What are objects and what are the objects in OC? An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects; What is a class? What […]