试图让客户端发送和接收文件(图像,文本文件) 问题是,有一种方法可以发送文件,而不必关闭套接字才能使其以后接收文件。 我发现我可以打开两个用于接收和发送的线程,但是我不能。 有什么办法可以通过添加新的套接字来实现这一点。
我的客户代码:
filename='48469.jpg'
TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 1024
s = socket.socket()
s.connect((TCP_IP, TCP_PORT))
f = open(filename,'rb')
while True:
l = f.read(BUFFER_SIZE)
while (l):
s.sendall(l)
#print('Sent ',repr(l))
l = f.read(BUFFER_SIZE)
if not l:
print ('file close()')
s.close()
#where I did closed the socket because
#otherwise the server wont stop from receiving data
f.close()
break
print("1")
f = open('received_from_server.txt', 'wb')
print ('file opened')
while True:
#print('receiving data...')
data = s.recv(BUFFER_SIZE)
if not data:
f.close()
print ('file close()')
break
# write data to a file
f.write(data)
print("2")
print('Successfully get the file')
s.close()
print('connection closed')
我的服务器代码:
filename='112.txt'
TCP_IP = 'localhost'
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):
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))
f = open('received_from_client.jpg', 'wb')
print ('file opened')
while True:
data = conn.recv(BUFFER_SIZE)
if not data:
print("8")
f.close()
print ('file close()')
break
# write data to a file
f.write(data)
print("1")
newthread = ClientThread(ip,port,conn)
print("2")
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
当前它向我显示错误
尝试对不是套接字的对象进行操作”