Python Socket - Why connection closed after sending several messages? -
Python Socket - Why connection closed after sending several messages? -
i have programme launches tcp client server, , can send messages , files client server (they transferred in direction). server expected listening, , respond each upcoming message. found after sent several messages, server never responds again, unless relaunch connect
button on gui.
here have in server
,
# found connection def conn(self): self.s = socket.socket(socket.af_inet, socket.sock_stream) self.s.bind((self.ip, self.port)) self.s.listen(1) print 'server ready.' self.conn, self.addr = self.s.accept() print 'connected by', str(self.addr), '\n' def recv(self): flag = self.conn.recv(buffer_size) info = self.conn.recv(buffer_size) # message if flag=='1': msg = "other >> %s" % info self.conn.send("success") print msg homecoming # there file elif flag=='0': filename = info open('new_'+filename, 'wb+') f: while true: info = self.s.recv(buffer_size) if not data: break # transfer finished f.write(data) size = os.path.getsize(filename) self.conn.send(str(size)) # echo size self.conn.send("success") homecoming # not close connection unless exception raised def run(self): self.conn() while true: try: # shoud connect 1 time again each time here? self.recv() except: self.close() break
and in client
have,
# expected found connection def conn(self): self.s = socket.socket(socket.af_inet, socket.sock_stream) print 'client ready.' try: self.s.connect((self.ip, self.port)) print 'connection established.' except: # close socket self.s.close() raise def send(self, msg='', flag=1): if flag: self.s.send(str(flag)) self.s.send(msg) sent = self.s.recv(buffer_size) print sent else: self.s.send(str(flag)) self.s.send(msg) # send filename # send file in buffer-size open(msg, 'rb') f: while 1: info = f.read(buffer_size) if not data: break self.s.send(data) # send block sent = self.s.recv(buffer_size) print 'sent: %s bytes' % sent
the problem is, should set client.socket.connect()
in each send
function or leave established , trust not down? , in server, should close connection after each message received? , why connection mysteriously downwards after short time?
another question noticed code examples transfer files server client using conn.send()
, instead, sent files client server socket.send()
. cause problem?
i think there wrong function name may cause problem.
change function name in server code:
... def connection(self): ... ... def run(self): self.connection() while true: ...
tell me if works.
python sockets
Comments
Post a Comment