Python 简单聊天室

#coding=utf-8

from  socket import *
from threading import Thread
import time

udpSocket = socket(AF_INET,SOCK_DGRAM)
bind = ('',38438)
udpSocket.bind(bind)

def sendData(ip,port):
    connectInfo = (ip,port)
    while True:
        msg = input("<<<")
        msg += "\n"
        udpSocket.sendto(msg.encode("gb2312"),connectInfo)

def recvData():
    while True:
        info = udpSocket.recvfrom(1024)
        dataInfo,destInfo = info
        ip,port = destInfo
        print("\r>>>[%s] %s : %s\n<<<"%(time.ctime(),ip,dataInfo.decode("gb2312")))

def main():
    ip = input("请输入对方IP:")
    port = int(input("请输入对方端口"))

    t1 = Thread(target=sendData,args=(ip,port,))
    t2 = Thread(target=recvData)

    t1.start()
    t2.start()

    t1.join()
    t2.join()

if __name__ == "__main__":
    main()

对端可以用Python写,也可以用netassist

posted @ 2018-03-05 17:10  精膘十三郎  阅读(373)  评论(0编辑  收藏  举报