转载

Python 之多线程应用

import socket
from threading import Thread

def recv_data():
    while True:
        recv_info = udp_socket.recvfrom(1024)
        print(">> %s:%s" % (recv_info[1], recv_info[0].decode("gbk")))
    pass

def send_data():
    while True:
        send_info = input("<<")
        udp_socket.sendto(send_info.encode("gbk"), (ip, port))
    pass

def main():
    global udp_socket
    global ip
    global port
    ip = input("对方的ip:")
    port = int(input("对方的port:"))
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind(("", 8080))
    tr = Thread(target=recv_data)
    ts = Thread(target=send_data)

    tr.start()
    ts.start()

    tr.join()
    ts.join()


if __name__ == "__main__":
    udp_socket = None
    ip = ""
    port = 0
    main()

 

转载于:https://www.cnblogs.com/yang-2018/p/10854071.html

正文到此结束
本文目录