代码:
import socket
import threading
def udpSend(udp_s,ip,port):
while True:
sendCont = input('请输入要发送的内容:')
udp_s.sendto(sendCont.encode(),(ip,port))
def udpRecv(udp_s):
while True:
recvCont = udp_s.recvfrom(1024)
print('收到的内容是:',recvCont)
def main():
udp_s = socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM)
udp_s.bind(('',7890))
ip = '192.168.137.100'
port = 8080
threadRecv = threading.Thread(target=udpRecv,args=(udp_s,))
threadSend = threading.Thread(target=udpSend,args=(udp_s,ip,port))
threadSend.start()
threadRecv.start()
threadSend.join()
threadRecv.join()
udp_s.close()
#udp_s.sendto()
if __name__ == '__main__':
main()
在这段代码中也体现出一个‘多线程遇到while True’的处理方案,在一个线程中做while True
在一个线程中死循环,玩命循环,就卡在这里,一个线程一直执行这项内容,并不影响其他的线程的运行,我之前想不明白这点事,现在想明白了。