import socket
import argparse
import re
import time
import os
import sys
import threading
import getpass
import hashlib
User = None
def get_md5_value(s):
my_md5 = hashlib.md5()
my_md5.update(s.encode('utf-8'))
md5_value = my_md5.hexdigest()
return md5_value
def register(sock):
while True:
while True:
UserName = input ('Please input your username(4-16 numbers or letters):\n')
if len(UserName) < 4:
print('Your name is too short!')
continue
elif len(UserName) > 16:
print('Your name is too long!')
continue
elif re.match(r'[a-zA-Z0-9]{4,16}$',UserName) == None:
print('Username is illegal!')
continue
else:
break
while True:
PassWord = input ('Please input your password(8-24 numbers or letters)\n')
if len(PassWord) < 8:
print('Your password is too short!')
continue
elif len(PassWord) > 24:
print('Your password is too long!')
continue
elif re.match(r'[a-zA-Z0-9]{8,24}$',PassWord) == None:
print('Password is illegal!')
continue
else:
PassWord1 = input('Input your password again:\n')
if PassWord1 != PassWord:
continue
else:
break
PassWord = get_md5_value(PassWord)
message = bytes(UserName,encoding = 'utf-8') + b',' + bytes(PassWord,encoding = 'utf-8')
sock.sendall(message)
serverback = sock.recv(1024).decode('utf-8')
if serverback == '0':
print('Username already exists')
continue
else:
print('Register successfully!')
time.sleep(1)
os.system('cls')
break
def log_in(sock):
global User
while True:
UserName = input ('Please input your username:\n')
PassWord = getpass.getpass('Please input your password:\n')
PassWord = get_md5_value(PassWord)
message = bytes(UserName,encoding = 'utf-8') + b',' + bytes(PassWord,encoding = 'utf-8')
User = UserName
sock.sendall(message)
serverback = sock.recv(1024).decode('utf-8')
if serverback == '0':
print('Incorrect username or password,please re-enter!')
continue
else:
print('Log in successfully!')
time.sleep(1)
os.system('cls')
break
if not os.path.exists('e:\\file_received\\'+UserName):
os.makedirs('e:\\file_received\\'+UserName)
def log_out(sock):
serverback = sock.recv(1024).decode('utf-8')
if serverback == '1':
print('Log out successfully!')
else:
print('Log out error!')
def find_online(sock):
online_users = sock.recv(1024).decode('utf-8').split(',')
for user in online_users:
print(user)
def recieve(sock):
while True:
try:
data = sock.recv(1024).decode('utf-8').split('|')
if data[1] == '$_-#&':
print('\n'+data[0]+' is offline or out of the chatting room,try to chat with others or exit.')
elif data[0] == 'server()' and data[1] == 'exit()':
os._exit()
else:
print(time.ctime()+' {}:\n {}\n'.format(data[0],data[1]))
except ConnectionError:
print('\nConnection error.')
sys.exit(1)
except:
#print('Exit successfully.')
sys.exit(1)
def send_sth(sock):
while True:
message = input('\n')
if '|' in message:
print('Sensitive character \'|\'')
continue
to_who = input('To:')
if '|' in to_who:
print('Sensitive character \'|\'')
continue
try:
sock.sendall((to_who+'|'+message).encode('utf-8'))
if message == 'exit()' and to_who == 'server()':
return (to_who,message)
except ConnectionError:
print('\nConnection error.')
sys.exit(1)
except:
print('\nUnexpected error.')
sys.exit(1)
def chat(sock):
print('/*You have joined the chatting moudle,send exit() to server() to end the moudle.*/')
threading._start_new_thread(recieve,(sock,))
send_sth(sock)
def send_file(sock):
while True:
path = input('File path:')
receiver = input('Receiver:')
if os.path.exists(path):
file_size = os.stat(path).st_size
sock.sendall(path.encode('utf-8')+b','+receiver.encode('utf-8')+b','+str(file_size).encode('utf-8'))
if sock.recv(1024) == b'-1':
print('No such receiver,try again.')
continue
else:
break
else:
print('No such file or directory,try again.')
f = open(path,'rb')
recved_size = int(sock.recv(1024).decode('utf-8'))
f.seek(recved_size)
print('Sending,wait for a while...')
for line in f:
data = sock.sendall(line)
if sock.recv(1024).decode('utf-8') == 'ok':
print('Successed.')
time.sleep(1)
def recv_file(sock):
while True:
filename = sock.recv(1024).decode('utf-8')
if filename == '-1':
print('No more file for you.')
break
else:
print('Ready to receive file:',filename)
if os.path.exists('e:\\file_received\\'+User+'\\'+filename):
recved_size = os.stat('e:\\file_received\\'+User+'\\'+filename).st_size
sock.sendall(str(recved_size).encode('utf-8'))
else:
recved_size = 0
sock.sendall(b'0')
file_size = int(sock.recv(1024).decode('utf-8'))
f = open('e:\\file_received\\'+User+'\\'+filename,'ab')
print('Receiving,wait for a while...')
while True:
data = sock.recv(1024)
f.write(data)
recved_size += len(data)
if recved_size == file_size:
break
f.close()
sock.sendall(b'ok')
print('Successed.')
def parse_command_line():
description = 'argument:[host][port]'
parser = argparse.ArgumentParser(description = description)
parser.add_argument('host',help = 'This is the server IP address.')
parser.add_argument('-p',help = 'Tcp port(default 6666)',metavar = 'port',type = int,default = 1060)
args = parser.parse_args()
address = (args.host,args.p)
return address
def client(address):
os.system('cls')
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(address)
print('========================================')
print('Easychat 1.0.0 ('+time.ctime()+')')
while True:
choice = input('1.Register 2.Login 3.Quit\n>>>')
if choice == '3':
os.system('cls')
sock.sendall(b'9')
print('See you next time.')
break
elif choice == '1':
os.system('cls')
sock.sendall(b'2')
register(sock)
elif choice == '2':
os.system('cls')
sock.sendall(b'3')
log_in(sock)
function = None
while True:
if function == '1' or function == '2':
os.system('cls')
print('====================================')
function = input('1.Chat 2.Send file 3.Recv file\n4.Find online users 5.Logout\n>>>')