0

I wrote a python client to communicate with server side. Each time when I finished sanding out data, I have to call sock.shutdown(socket.SHUT_WR), otherwise the server would not do any response. But after calling sock.shutdown(socket.SHUT_WR), I have to reconnect the connection as sock.connect((HOST, PORT)), other wise I can not send data to server. So how can I keep the connection alive without close it. My sample code as following:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.sendall(data)
sock.shutdown(socket.SHUT_WR)
received = sock.recv(1024)
while len(received)>0:
    received = sock.recv(1024)
sock.sendall(newdata) # this would throw exception

The Server Side code as following:

def handle(self):
    cur_thread = threading.current_thread()
    while True:
        self.data = self.rfile.read(bufsiz=100)
        if not self.data:
            print 'receive none!'
            break
        try:
            data = self.data
            print 'Received data, length: %d' % len(data)
            self.wfile.write('get received data\n')
        except Exception:
            print 'exception!!'
0

1 Answer 1

1

You didn't show any server side code but I suspect it simply reads bytes until it gets none anymore.

You can't do this as you found out, because then the only way to tell the server the message is complete is by killing the connection.

Instead you'll have to add some form of framing in your protocol. Possible approaches include a designated stop character that the server recognises (such as a single newline character, or perhaps a 0-byte), sending frames in fixed sizes that your client and server agree upon, or send the frame size first as a network encoded integer followed by exactly the specified number of bytes. The server then first reads the integer and then exactly that same number of bytes from the socket.

That way you can leave the connection open and send multiple messages.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.