1. 程式人生 > >利用Python實現多執行緒聊天功能

利用Python實現多執行緒聊天功能

#-*- 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()