SoFunction
Updated on 2024-11-16

Python implementation of a multitasking version of the udp chater

In this article, we share an example of Python implementation of the multitasking version of the udp chatter for your reference, the details are as follows

I. Case examples

II. Description of cases

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

III. Reference codes

import socket
import threading


def send_msg(udp_socket):
    """Get keyboard data and send it to each other."""
    while True:
        # 1. Data entry from keyboard
        msg = input("\n Please enter the data to be sent:")
        # 2. Enter the other party's ip address
        dest_ip = input("\n Please enter the other party's ip address:")
        # 3. Enter the other side's port
        dest_port = int(input("\n Please enter the other side's port:"))
        # 4. Send data
        udp_socket.sendto(("utf-8"), (dest_ip, dest_port))


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


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

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


if __name__ == "__main__":
    main()

This is the whole content of this article.