聊天室1里的代码

from socket import *
from threading import Thread

# 创建sock对象
udpSock1 = socket(AF_INET, SOCK_DGRAM)
# 绑定ip地址端口
udpSock1.bind(("", 8880))


# 发送数据
def sendDate():
    while 1:
        date = input("")
        udpSock1.sendto(date.encode(), ("192.168.3.2", 8085))


# 接收数据
def recveDate():
    while 1:
        receDate = udpSock1.recvfrom(1024)
        print(receDate[0].decode())
    udpSock1.close()

# 创建线程
t1 = Thread(target=sendDate)
t2 = Thread(target=recveDate)
t1.start()
t2.start()

聊天室2的代码

from socket import *
from threading import Thread

# 创建sock对象
udpSock1 = socket(AF_INET, SOCK_DGRAM)
# 绑定ip地址端口
udpSock1.bind(("", 8085))
# 接收数据
def recveDate():
    while 1:
        global receDate
        receDate = udpSock1.recvfrom(1024)
        print(receDate[0].decode())
    udpSock1.close()

# 发送数据
def sendDate():
    while 1:
        date = input("")
        udpSock1.sendto(date.encode(), receDate[1])

# 创建线程
t1 = Thread(target=sendDate)
t2 = Thread(target=recveDate)
t1.start()
t2.start()

现在的问题是,当聊天室1不输入内容,聊天室2先输就报错。看错误是聊天室2receDate没定义,没先接收到数据,有没有一种好的解决方案呢。

image.png

相关课程:Python全系列>第三阶段:Python 网络与并发编程>网络通信>UDP编程1_服务器接收数据经典案例

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637