我尝试制作一个简单的服务器
a)客户端连接后立即发送文件 b)以后在编辑文件时接收文件
和一个客户端,该客户端在连接时会自动接收文件并稍后发送经过编辑的文件
因此对于接收第一部分的客户端部分来说,它工作正常,但是如果满足条件,如何发回文件
TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
with open('received_file', 'wb') as f:
print( 'file opened')
while True:
#print('receiving data...')
data = s.recv(BUFFER_SIZE)
print('data=%s', (data))
if not data:
f.close()
print( 'file close()')
break
# write data to a file
f.write(data)
s.close()
print('Successfully get the file')
if time.sleep(3):
s.connect((TCP_IP, TCP_PORT))
with open('answer.txt', 'rb') as f:
print( 'file opened')
while True:
#print('receiving data...')
data = s.send(BUFFER_SIZE)
print('data=%s', (data))
print('Successfully send the file')
s.close()
print('connection closed')
服务器
TCP_IP = "0.0.0.0"
TCP_PORT = 9001
BUFFER_SIZE = 1024
class ClientThread(Thread):
def __init__(self,ip,port,sock):
Thread.__init__(self)
self.ip = ip
self.port = port
self.sock = sock
print( " New thread started for "+ip+":"+str(port))
def run(self):
filename='filetosend.csv'
f = open(filename,'rb')
while True:
l = f.read(BUFFER_SIZE)
while (l):
self.sock.send(l)
#print('Sent ',repr(l))
l = f.read(BUFFER_SIZE)
if not l:
f.close()
self.sock.close()
break
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpsock.listen(5)
print("Waiting for incoming connections...")
(conn, (ip,port)) = tcpsock.accept()
print( 'Got connection from ', (ip,port))
newthread = ClientThread(ip,port,conn)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
我应该在哪里和什么地方收听客户端发送的文件?
客户端的发送部分是否正确?