国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現簡單聊天應用 python群聊和點對點均實現

2020-02-16 10:14:40
字體:
來源:轉載
供稿:網友

后續代碼更新和功能添加會提交到個人github主頁,有興趣可以一起來完善!

如果只是拿過去運行看結果,請注意平臺相關性以及python版本號,本示例開發運行平臺為win7x86_64 pycharm community,python版本號為3.5!!!

TALK IS CHEAP, SHOW YOU MY CODE:

客戶端

#coding:utf-8'''file:client.py.pydate:2017/9/11 11:01author:lockeyemail:lockey@123.complatform:win7.x86_64 pycharm python3desc:p2p communication clientside'''from socket import *import threading,sys,json,re#引入json模塊主要是為了數據的封裝傳輸,re的話是做一些合法性的驗證HOST = '192.168.1.7'PORT=8022BUFSIZE = 1024 ##緩沖區大小 1KADDR = (HOST,PORT)myre = r"^[_a-zA-Z]/w{0,}"tcpCliSock = socket(AF_INET,SOCK_STREAM)#創建一個socket連接userAccount = None#用戶登錄標志,也用來記錄登錄的用戶名稱def register():#用戶注冊函數 print(""" Glad to have you a member of us! """) accout = input('Please input your account: ') if not re.findall(myre, accout):  print('Account illegal!')  return None password1 = input('Please input your password: ') password2 = input('Please confirm your password: ') if not (password1 and password1 == password2):  print('Password not illegal!')  return None global userAccount userAccount = accout regInfo = [accout,password1,'register'] datastr = json.dumps(regInfo) tcpCliSock.send(datastr.encode('utf-8')) data = tcpCliSock.recv(BUFSIZE) data = data.decode('utf-8') if data == '0':  print('Success to register!')  return True elif data == '1':  print('Failed to register, account existed!')  return False else:  print('Failed for exceptions!')  return Falsedef login():#用戶登錄函數 print(""" Welcome to login in! """) accout = input('Account: ') if not re.findall(myre, accout):  print('Account illegal!')  return None password = input('Password: ') if not password:  print('Password illegal!')  return None global userAccount userAccount = accout loginInfo = [accout, password,'login'] datastr = json.dumps(loginInfo) tcpCliSock.send(datastr.encode('utf-8')) data = tcpCliSock.recv(BUFSIZE) if data == '0':  print('Success to login!')  return True else:  print('Failed to login in(user not exist or username not match the password)!')  return Falsedef addGroup():#群組添加 groupname = input('Please input group name: ') if not re.findall(myre, groupname):  print('group name illegal!')  return None return groupnamedef chat(target):#進入聊天(群聊和點對點聊天可以選擇) while True:  print('{} -> {}: '.format(userAccount,target))  msg = input()  if len(msg) > 0 and not msg in 'qQ':   if 'group' in target:    optype = 'cg'   else:    optype = 'cp'   dataObj = {'type': optype, 'to': target, 'msg': msg, 'froms': userAccount}   datastr = json.dumps(dataObj)   tcpCliSock.send(datastr.encode('utf-8'))   continue  elif msg in 'qQ':   break  else:   print('Send data illegal!')class inputdata(threading.Thread):#用戶輸入選擇然后執行不同的功能程序 def run(self):  menu = """      (CP): Chat with individual      (CG): Chat with group member      (AG): Add a group      (EG): Enter a group      (H): For help menu      (Q): Quit the system      """  print(menu)  while True:   operation = input('Please input your operation("h" for help): ')   if operation in 'cPCPCpcp':   #進入個人聊天    target = input('Who would you like to chat with: ')    chat(target)    continue   if operation in 'cgCGCgcG':   #進入群聊    target = input('Which group would you like to chat with: ')    chat('group'+target)    continue   if operation in 'agAGAgaG':   #添加群組    groupName = addGroup()    if groupName:     dataObj = {'type': 'ag', 'groupName': groupName}     dataObj = json.dumps(dataObj)     tcpCliSock.send(dataObj.encode('utf-8'))    continue   if operation in 'egEGEgeG':   #入群    groupname = input('Please input group name fro entering: ')    if not re.findall(myre, groupname):     print('group name illegal!')     return None    dataObj = {'type': 'eg', 'groupName': 'group'+groupname}    dataObj = json.dumps(dataObj)    tcpCliSock.send(dataObj.encode('utf-8'))    continue   if operation in 'hH':    print(menu)    continue   if operation in 'qQ':    sys.exit(1)   else:    print('No such operation!')class getdata(threading.Thread):#接收數據線程 def run(self):  while True:   data = tcpCliSock.recv(BUFSIZE).decode('utf-8')   if data == '-1':    print('can not connect to target!')    continue   if data == 'ag0':    print('Group added!')    continue   if data == 'eg0':    print('Entered group!')    continue   if data == 'eg1':    print('Failed to enter group!')    continue   dataObj = json.loads(data)   if dataObj['type'] == 'cg':   #群組消息的格式定義    print('{}(from {})-> : {}'.format(dataObj['froms'], dataObj['to'], dataObj['msg']))   else:   #個人消息的格式定義    print('{} ->{} : {}'.format(dataObj['froms'], userAccount, dataObj['msg']))def main():  try:   tcpCliSock.connect(ADDR)   print('Connected with server')   while True:    loginorReg = input('(l)ogin or (r)egister a new account: ')    if loginorReg in 'lL':     log = login()     if log:      break    if loginorReg in 'rR':     reg = register()     if reg:      break   myinputd = inputdata()   mygetdata = getdata()   myinputd.start()   mygetdata.start()   myinputd.join()   mygetdata.join()  except Exception:   print('error')   tcpCliSock.close()   sys.exit()if __name__ == '__main__': main()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 普定县| 漾濞| 达孜县| 灵武市| 无为县| 渝中区| 海兴县| 杭锦旗| 友谊县| 肃宁县| 南木林县| 襄城县| 米易县| 太湖县| 乳山市| 鹤山市| 鄯善县| 迁西县| 台南市| 佛教| 山东省| 吉水县| 绥中县| 澎湖县| 文昌市| 金秀| 内乡县| 漠河县| 什邡市| 蓬安县| 衡南县| 石柱| 贡觉县| 荆州市| 高密市| 富阳市| 平陆县| 广元市| 屯留县| 铜鼓县| 应城市|