python-1802-和卓 15:12:36
1……
from threading import Thread
class SenderThread(Thread):? ?
? ? ? ? ? ? ? ? ? def__init__(self,socket,destaddress,d estport): ? ? ? ?
? Thread.__init__(self)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.socket = socket? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.dest_address = destaddress ? ? ? ? ? self.dest_port = destport ? ?
def run(self): ? ? ? ?
? ? while True: ? ? ? ? ? ? ?
? ? ? ? msg = input("我說(shuō):")? #鍵盤(pán)輸入? ? ? ? ? ? ? ? ? ? ? ? self.socket.sendto(msg.encode(),(self.dest_address,self.dest_port))
2……
from threading import
Thread class ReceiverThread(Thread): 接收線程 ? ? def __init__(self,socket):? ? ? ? ? ? ? Thread.__init__(self) ? ? ? ? self.socket = socket? ? ?
def run(self): ? ? ? ?
? ? while True: ? ? ? ? ? ?
? ? ? ? msg,addr = self.s.recvfrom(1024) ? ? ? ? ? ? ? print(addr,"說(shuō):",msg.decode())
3……
import socket
from chat_sender import SenderThread
from chat_receiver import ReceiverThread
s = socket.socket(type=socket.SOCK_DGRAM)? #實(shí)例化支持UDP協(xié)議的socket對(duì)象
s.bind(("localhost",8888))
SenderThread(socket,"localhost",6666).start() #啟動(dòng)發(fā)送線程
ReceiverThread(s).start() #啟動(dòng)接收線程