Python Socket - 发送多条消息后为什么连接关闭?

时间:2014-10-18 10:03:45

标签: python sockets

我有一个启动TCP客户端和服务器的程序,我可以将消息和文件从客户端发送到服务器(它们都是按此方向传输的)。期望服务器始终在监听,并响应每个即将发布的消息。但是在我发送了几条消息后,我发现服务器再也没有响应,除非我重新启动GUI上的connect按钮。

这里我们有server

# establish 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)
    data = self.conn.recv(BUFFER_SIZE)

    # this is a message
    if flag=='1':
        msg = "other >> %s" % data
        self.conn.send("success")
        print msg
        return

    # there will be a file  
    elif flag=='0':
        filename = data
        with open('new_'+filename, 'wb+') as f:
            while True:
               data = 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")
        return

# do not close connection unless exception raised
def run(self):
    self.conn()
    while True:
        try:
            # shoud I connect again each time here?
            self.recv()
        except:
            self.close()
            break

并且在client我有,

# expected to establish a 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
        with open(msg, 'rb') as f:
            while 1:
                data = 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

问题是,我应该将client.socket.connect()放在每个send函数中,还是只是让它保持建立并相信它不会失效?在服务器中,我应该在收到每条消息后关闭连接吗?为什么我的联系在短时间内神秘地消失了?

另一个问题是我注意到一些代码示例使用conn.send()将文件从服务器传输到客户端,而我通过socket.send()将文件从客户端发送到服务器。这会导致问题吗?

1 个答案:

答案 0 :(得分:2)

我认为功能名称有问题可能导致您的问题。

更改服务器代码中的函数名称:

...
def connection(self):
...

...
def run(self):
    self.connection()
    while True:
...

告诉我它是否有效。