GUI当客户端输入“send a file”,服务器端回复“please input the file name:”(在客户端显示)。
(本文代码已实现)当客户端输入文件名后,服务器端如果有该文件,则发送该文件,否则回复客户端“This file does not exist”(此处博主建议采用异常处理)。客户端打印接收到的文件内容。
服务端发送程序参考如下:
if data =='send a file':
data = conn.recv(1024).decode()
filename = data
file_size = os.path.getsize(filename)
fhead = struct.pack('l', file_size)
s.sendall(fhead)
fp =open(filename,'rb')whileTrue:
data = fp.read(1024)ifnot data:break
s.sendall(data)
fp.close()print("send over")
(选)实现服务器与多客服通信功能。(线程实现)
多客服端参考代码如下:
import socket
from threading import Thread
from os.path import commonprefix
BUFSIZE=1024defreply(conn):# 开始聊天whileTrue:
data = conn.recv(1024).decode()ifnot data:breakprint('Received message:', data)
m =0
key =''for k in words.keys():
data =' '.join(data.split())iflen(commonprefix([k, data]))>len(k)*0.7:
key = k
break
length =len(set(data.split())&set(k.split()))if length > m:
m = length
key = k
# 选择合适的信息进行回复
conn.sendall(words.get(key,'Sorry.').encode())
conn.close()
words ={'how are you?':'Fine,thank you.','how old are you?':'38','what is your name?':'Dong FuGuo',"what's your name?":'Dong FuGuo','where do you work?':'University','bye':'Bye','send a file':'please input the file name:'}
HOST ='192.168.1.103'
PORT =5007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 绑定socket
s.bind((HOST, PORT))# 开始监听一个客户端连接
s.listen(50)print('Listening on port:',PORT)whileTrue:
conn, addr = s.accept()print('Connected by', addr)
Thread(target=reply, args=(conn,)).start()
s.close()
# -*- coding: utf-8 -*-"""
Created on 2021-12-21 下午 07:47
@author: 浅笑醉红楼.(3303295829@qq.com)
@Software: PyCharm
(1) create by 浅笑醉红楼. 2021-12-21 下午 07:47
"""import socket
from os.path import commonprefix
words={'how are you?':'Fine,thank you.','how old are you?':'38','what is your name?':'DongFuGuo',"what's your name?":'DongFuGuo','where do you work?':'SDIBT','bye':'Bye','send a file':'please input the file name:'}
HOST=''#IP地址
PORT=5007
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)# 绑定scoket
s.bind((HOST,PORT))# 开始监听
s.listen(1)print('Listening at port:',PORT)
conn,addr=s.accept()print('Connected by',addr)whileTrue:
data = conn.recv(1024).decode()ifnot data:breakprint('Received message:', data)
m =0
key =''for k in words.keys():
data =' '.join(data.split())iflen(commonprefix([k, data]))>len(k)*0.7:
key = k
break
length =len(set(data.split())&set(k.split()))if length > m:
m = length
key = k
conn.sendall(words.get(key,'Sorry.').encode())try:if data =='send a file':
data = conn.recv(1024).decode()
filename = data
file_size = os.path.getsize(filename)
fhead = struct.pack('l', file_size)
s.sendall(fhead)
fp =open(filename,'rb')whileTrue:
data = fp.read(1024)ifnot data:break
s.sendall(data)
fp.close()print("send over")except Exception as e:
conn.sendall(words.get(data,'This file does not exist').encode())print("传输异常:", e)
conn.close()
s.close()