#-*- coding:utf-8 -*-
from threading import Thread
from socket import *
#1.实现接收消息
def recvDate():
while True:
recvInfo = udpSocket.recvfrom(1024)
print("\r\n>>%s:%s"%(str(recvInfo[1]),recvInfo[0].decode("gb2312")))
print("<<") #2.实现发送消息
def sendDate():
while True:
sendInfo = input("<<")
udpSocket.sendto(sendInfo.encode("gb2312"),(destIp,destPort)) udpSocket = None
destIp = ""
destPort = 0 def main():
#改变全局变量时才加global
global udpSocket
global destIp
global destPort udpSocket = socket(AF_INET, SOCK_DGRAM) destIp = input("请输入目的ip:")
destPort = int(input("请输入目的端口:"))
localPort = int(input("请输入本程序的端口号:"))
udpSocket.bind(("",localPort)) #绑定端口号
re = Thread(target = recvDate) #线程1
rh = Thread(target = sendDate) #线程2 re.start()
rh.start() re.join() #等待至线程中止
rh.join() if __name__ == "__main__":
main()