server端
import os
from socket import socket
import hashlib
def chat(connect: socket, address):
while True:
message = input('>>>')
connect.send(message.encode())
if message in ['拜拜', '再見', 'Bye-Bye']:
return
re_message = connect.recv(1024).decode(encoding='utf-8')
print(f'{address[0]}:{re_message}')
if re_message in ['拜拜', '再見', 'Bye-Bye']:
return
def send_image(connect: socket):
all_image_name = os.listdir('./serverImage')
message = ''
for index, item in enumerate(all_image_name):
message += f'{index}.{item} '
connect.send(message.encode())
index = connect.recv(1024).decode(encoding='utf-8')
try:
if 0 <= int(index) < len(all_image_name):
image_name = all_image_name[int(index)]
print('傳送圖片...')
with open('serverImage/'+image_name, 'rb') as f:
image_content = f.read()
hash = hashlib.md5()
hash.update(image_content)
digest = hash.hexdigest()
connect.send(digest.encode())
connect.send(image_content)
else:
print('取消圖片傳送')
except ValueError:
print('取消圖片傳送')
def create_server():
server = socket()
server.bind(('10.7.165.86', 4568))
server.listen(200)
while True:
print('等待.....')
connect, address = server.accept()
while True:
message = connect.recv(1024).decode(encoding='utf-8')
if message == 'chat':
print('聊天')
chat(connect, address)
elif message == 'image':
print('發圖片')
send_image(connect)
elif message == 'close':
connect.close()
break
if __name__ == '__main__':
create_server()
client端
import re
from socket import socket
import hashlib
import uuid
def get_digest(data):
hash = hashlib.md5()
hash.update(data)
return hash.hexdigest()
def chat(client):
client.send('chat'.encode(encoding='utf-8'))
while True:
re_message = client.recv(1024).decode(encoding='utf-8')
print('伺服器:'+re_message)
if re_message in ['拜拜', '再見', 'Bye-Bye']:
return
message = input('客戶端:')
client.send(message.encode())
if message in ['拜拜', '再見', 'Bye-Bye']:
return
def get_image(client):
client.send('image'.encode(encoding='utf-8'))
image_message = client.recv(1024).decode(encoding='utf-8')
print(image_message+'')
index = input('請選擇(輸入標號,如果不需要輸入其他值):')
client.send(index.encode())
all_index = re.findall(r'\b(\d+)\.', image_message)
if index in all_index:
print('接受圖片')
digest = client.recv(1024).decode(encoding='utf-8')
image_data = bytes()
while True:
image_data += client.recv(2048)
if get_digest(image_data) == digest:
print('圖片接受完成')
with open('clientImage/'+uuid.uuid4().hex, 'wb') as f:
f.write(image_data)
break
else:
print('不接受圖片')
def close_connection(client):
client.send('close'.encode(encoding='utf-8'))
client.close()
exit()
def create_client():
client = socket()
client.connect(('10.7.165.86', 4568))
while True:
print('1. 聊天\n2. 獲取圖片\n3. 斷開連線')
value = input('請選擇(1~3):')
if value == '1':
chat(client)
elif value == '2':
get_image(client)
elif value == '3':
print('斷開連線')
close_connection(client)
else:
print('輸入有誤!')
if __name__ == '__main__':
create_client()