python 多人聊天DOS版

DOS版,支持登陆,注销,命令行等操作,写的比较简单,仅供参考学习。

参考资料http://www.cnblogs.com/huxi/archive/2010/06/26/1765808.html

参考资料http://www.oschina.net/code/snippet_1387924_25928

客户端:

#coding=GBK
'''
Created on 2014/3/18
@author: LING
'''
import socket
import threading
import random
import time
import os

class QFclient(object):
    def __init__(self,my_socket):
        self.name=''
        self.socket=my_socket
        self.sendstr=''
        self.recvstr=''
        self.isLogon=False
        
    def send(self,s):
        while True:
            try:
                self.sendstr=raw_input()
                self.sendstr=self.sendstr.strip(' ')
                if 'command ' == self.sendstr[:8]:
                    if self.sendstr[8:]=='dir' or self.sendstr[8:]=='ls':
                        os.system('dir')
                    else:
                        os.system(self.sendstr[8:])  
                elif 'login ' ==self.sendstr[:6]:
                    self.name=self.sendstr[6:].strip(' ').split(' ')[0]
                    s.send(self.sendstr)
                elif '--help' == self.sendstr[:6]:
                    print '======================================'
                    print 'login -user -password //登陆系统'
                    print 'command -expr         //执行DOS命令'
                    print '-version              //查看当前版本'
                    print 'request -user -ls     //查看用户组状态'
                    print 'request -file -ls    //查看群共享(需要登陆)'
                    print 'request -download -filename    //下载文件,filename为文件名(需要登陆)'
                    print 'request -upload -filepath     //上传件,filepath为文件路径(需要登陆)'
                    print 'request -logoff                //退出系统'
                    print '======================================'   
                elif '-version'==self.sendstr[:8]:   
                    print '***  这是一个复杂的多人聊天室程序        ***'
                    print '***@author: ling  @version: v1.0.0***'  
                elif self.isLogon==True:
                    self.sendstr=self.name+':'+self.sendstr
                    s.send(self.sendstr)
            except Exception,e:
                break
    
    def recv(self,s):
        while True:
            try:
                self.recvstr=s.recv(1024)
                if not self.recvstr:
                    break
                if self.recvstr !=self.sendstr:
                    if  self.isLogon==False:
                        if self.recvstr=='response:ok':
                            os.system('cls')
                            print '***登陆成功,现在你可以聊天啦***'
                            self.isLogon=True
                        elif self.recvstr=='response:logoff ok':
                            self.isLogon=False
                            print '成功退出'
                        else:
                            print self.recvstr
                    else:
                        print self.recvstr
            except Exception,e:
                break
    
    def start(self):
        os.system('color 0a')
        sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        try:
            sock.connect(self.socket)
            print '***欢迎使用DOS QF客户端,请先登陆或者注册账号,帮助请输入--help***'
        except Exception,e:
            print 'QF服务器已跪,3秒后自动退出'
            time.sleep(3)
            return

        sock.send(self.socket[0])
        thrdin=threading.Thread(target=self.recv,args=(sock,)).start()
        thrdout=threading.Thread(target=self.send,args=(sock,)).start()
    
        
        
if __name__=='__main__':
    mysock=('127.0.0.1',8888)
    aclient=QFclient(mysock)  
    aclient.start()
    

服务端:

#coding=GBK
'''
Created on 2014/3/18
@author: LING
'''
import socket
import sys
import threading
import os
import time

class QFserver(object):
    def __init__(self,my_socket):
        self.con=threading.Condition()#条件变量
        self.socket=my_socket
        self.data=''
        self.onlineUser=0
        self.connectUser=0
        self.users={'li':{'state':0,'pass':'123456'},
                    'zhang':{'state':0,'pass':'123456'},
                    'ding':{'state':0,'pass':'123456'}}
    
    def start(self):
        os.system('color 0a')
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        print 'QF服务器成功开启!'
        s.bind(self.socket)
        s.listen(30)
        print 'QF服务器正在监听客户端连接...'
        while True:
            conn,addr=s.accept()
            print addr[0]+':'+str(addr[1])+'连接'
            name=conn.recv(1024)
            print self.data
            conn.send(self.data)
            isLogon=False
            self.connectUser+=1
            threading.Thread(target=self.ClientIn,args=(conn,name,isLogon)).start()
        s.close()
        
    def ClientIn(self,conn,name,isLogon):
        while True:
            try:
                temp=conn.recv(1024).strip(' ')#等待客户端发送信息
                if not temp:
                    conn.close()
                    return
                if isLogon==False:
                    if temp[:6]=='login ':
                        user=temp[6:].strip(' ').split(' ')
                        print user[0]+':'+user[1]
                        print self.users[user[0]].get('pass')
                        if user[0] in self.users and user[1]==self.users[user[0]].get('pass') and 0==self.users[user[0]].get('state'): 
                            if self.users[user[0]].get('state')==0:
                                self.users[user[0]]['state']=1
                            conn.send('response:ok')
                            isLogon=True
                            self.onlineUser+=1
                            name=temp[6:].split(' ')[0]
                            print name+'成功登录!'
                            print self.UserState()
                            threading.Thread(target=self.ClientOut,args=(conn,name)).start()

                        elif self.users[user[0]].get('state')==1:
                            conn.send('您的账号已在别处登录!')
                        else:
                            conn.send('账号密码错误')
                    else:
                        conn.send('请先登陆...')
                elif isLogon==True:
                    cmd=temp.split(':')
                    if cmd[1][:8]=='request ':
                        if cmd[1][8:]=='user ls':
                            conn.send('response:'+self.UserState())
                        elif cmd[1][8:]=='logoff':
                            conn.send('response:logoff ok')
                            self.onlineUser-=1
                            isLogon=False
                        elif cmd[1][8:]:
                            conn.send('您的版本过低,请升级客户端...')
                    else:
                        self.NotifyAll('>>>'+temp)#收到信息后激活所有输出线程
                    print self.data
            except Exception,e:
                if isLogon == True:
                    self.NotifyAll(name+'离开了')
                    isLogon==False
                    self.onlineUser-=1
                    self.connectUser-=1
                    self.users[user[0]]['state']=0
                print self.data
                return

    def ClientOut(self,conn,name):
        while True:
            if self.con.acquire():#获得锁定
                self.con.wait()#使线程进入condition等待池,并释放锁,等待通知
                if self.data:#如果被激活并且收到服务端数据开始群发
                    try:
                        conn.send(self.data)
                    except Exception,e:
                        return
                    finally:
                        self.con.release()#释放锁
    
    def NotifyAll(self,str):
        if self.con.acquire():#加锁
            self.data=str
            self.con.notifyAll()#激活,将等待池中所有线程置入等待池,尝试获得锁定
            self.con.release()#释放锁
   
    def UserState(self):
        s= '当前'+str(self.connectUser) + '人建立连接,'+\
            str(self.onlineUser)+'人在线'
        return s

if __name__=='__main__':
    mysock=('127.0.0.1',8888)
    aserver=QFserver(mysock)
    aserver.start()
        

运行截图:

python 多人聊天DOS版

上一篇:Confluence 6 XML 备份恢复失败的问题解决


下一篇:Confluence 6 XML 备份失败的问题解决