多用户,多房间全双工聊天,多用户房间全双工,mcs.py#!/usr


mcs.py

#!/usr/bin/env python# _*_ coding: utf8 _*_from socket import *from time import ctimeimport threadingfrom string import splitHOST = ''PORT = 21567BUFSIZE = 1024ADDR = (HOST, PORT)def Deal(sck, username, room):    while True:        data = sck.recv(BUFSIZE)        for i in  clients[room].iterkeys():            if i <> username:                if data <> "quit":                    clients[room][i].send("[%s] %s: %s" %(ctime(), username, data))                else:                    clients[room][i].send("用户%s在%s退出房间%s" %(username, ctime(), room ))        if data == "quit":            del clients[room][username]             sck.send(data)            sck.close()            breakchatSerSock = socket(AF_INET, SOCK_STREAM)chatSerSock.bind(ADDR)chatSerSock.listen(5)clients = {"":{},}while True:    print 'waiting for connection...'    chatCliSock, addr = chatSerSock.accept()    print "...connected romt: ", addr    data = chatCliSock.recv(BUFSIZE)    username, room = split(data)    print username    if not clients.has_key(room):        clients[room] = {}    if clients[room].has_key(username):        chatCliSock.send("reuse")        chatCliSock.close()    else:        chatCliSock.send("success")        clients[room][username] = chatCliSock        t = threading.Thread(target=Deal, args=(chatCliSock, username, room))        t.start()chatSerSock.close()

mcc.py

#!/usr/bin/env python# _*_ coding: utf8 _*_from socket import *from time import ctimeimport threadingimport randomfrom sys import argv, exit, stdoutfrom getopt import gnu_getopt, GetoptErrorhelp_info = ["cs.py [ -h | --help | -u | --username] username",    "\t-h or --help\t显示帮助信息",    "\t-u or --username\指定用户名",    "\t-r or --room\t指定房间"]def help():    for i in help_info:        print idef Send(sck, test):    while True:        data = raw_input('>')        sck.send(data)        if  data == "quit":            breakdef Recieve(sck, test):    while True:        data = sck.recv(BUFSIZ)        if data == "quit":            sck.close()            break        str = "\n" + data + "\n>"         stdout.write(str)HOST = 'localhost'PORT= 21567BUFSIZ = 1024ADDR = (HOST, PORT)threads = []if __name__ == "__main__":    # 解析命令行参数    try:        opts, args = gnu_getopt(argv[1:], "hu:r:", ["help", "username=", "room="])          except GetoptError, err:        print str(err)        help()        exit(2)    username = ""    room = ""    for o, a in opts:        if o in ("-h", "--help"):            help()            exit(0)        elif o in ("-u", "--username"):            username = a        elif o in ("-r", "--room"):            room = a        else:            print "未知选项"            help()            exit(2)    if not username or not room:        help()        exit(2)    chatCliSock = socket(AF_INET, SOCK_STREAM)    chatCliSock.connect(ADDR)    chatCliSock.send("%s %s" %(username, room))    data = chatCliSock.recv(BUFSIZ)    if data == "reuse":        print "用户%s已登录房间%s" %(username, room)        raw_input()        exit(1)    elif data == "success":        print "用户%s成功登录房间%s" %(username, room)        t = threading.Thread(target=Send, args = (chatCliSock, None))        threads.append(t)        t = threading.Thread(target=Recieve, args = (chatCliSock, None))        threads.append(t)        for i in range(len(threads)):            threads[i].start()        threads[0].join()

评论关闭