zoukankan      html  css  js  c++  java
  • 利用Python实现多线程聊天功能

    #-*- coding:utf-8 -*-
    from threading import Thread
    from socket import *
    #1.实现接收消息
    def recvDate():
        while True:
            recvInfo = udpSocket.recvfrom(1024)
            print("
    >>%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()

  • 相关阅读:
    N++ 道ASP.NET面试题
    Console-算法:fun1(do while)
    软件业:印度比中国强在哪
    印度软件业崛起的奥妙
    算法目录
    scala目录
    scala命令
    Spark目录
    Ubuntu目录
    Java核心技术卷二部分笔记
  • 原文地址:https://www.cnblogs.com/pythonClub/p/10252068.html
Copyright © 2011-2022 走看看