(32)--使用Socket--udp实现简单的聊天软件

#用Socket实现简单QQ对话

#服务端


import socket
from threading import Thread

# 定义处理接受消息的线程
def recfunc():
    global addr
    data,addr=s_udp.recvfrom(1024)
    print('>>:'+(data.decode('utf-8')))

# 定义处理发送消息的线程
def sendfunc():
    dataInput=input('<<:')
    s_udp.sendto(dataInput.encode('utf-8'),addr)
s_udp = None
addr =None

# 定义主函数功能
def min():
    global s_udp
    s_udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s_udp.bind(('',8752))

    while True:
        hr = Thread(target=recfunc())
        hs = Thread(target=sendfunc())

        hr.start()
        hs.start()

        hr.join()
        hs.join()
    s_udp.close()


min()


#客户端


import socket
from threading import Thread


# 1.收数据,打印
def recData():
    while True:
        data,addr=udpsocket.recvfrom(1024)
        print('>>'+(data.decode('utf-8')))

# 2.发数据
def sendData():
    while Thread:
        senInput=input('<<:')
        udpsocket.sendto(senInput.encode('utf-8'),(destIp,destPort))
udpsocket = None
destIp = ''
destPort = 0
def min():
    global udpsocket
    global destIp
    global destPort
    destIp = input('对方的IP:')
    destPort=int(input('对方的端口号:'))
    udpsocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udpsocket.bind(('',7853))

    tr = Thread(target=recData)
    th = Thread(target=sendData)

    tr.start()
    th.start()

    tr.join()
    th.join()
    udpsocket.close()

min()




兄弟连学python


Python学习交流、资源共享群:563626388 QQ


你可能感兴趣的:(Web基础)