python實現簡單聊天應用 python群聊和點對點均實現
阿新 • • 發佈:2021-06-22
如果只是拿過去執行看結果,請注意平臺相關性以及python版本號,本示例開發執行平臺為win7x86_64 pycharm community,python版本號為3.5!!!
TALK IS CHEAP, SHOW YOU MY CODE:
客戶端
#coding:utf-8
'''
file:client.py.py
date:2017/9/11 11:01
author:lockey
email:[email protected]
platform:win7.x86_64 pycharm python3
desc:p2p communication clientside
'''
from socket import *
import threading,sys,json,re
#引入json模組主要是為了資料的封裝傳輸,re的話是做一些合法性的驗證
HOST = '192.168.1.7'
PORT=8022
BUFSIZE = 1024 ##緩衝區大小 1K
ADDR = (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 False
def 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 ==