开发者

Reading data send from StreamRequestHandler write

I have a SocketServer.StreamRequestHandler server that calls self.rfile.readline() to read a request and then calls self.wfile.write(data) to send back some data:

class FileServerHandler(SocketServer.StreamRequestHandler):

    def handle(self):
            # self.rfile is a file-like oject created by the handler
            data = self.rfile.readline()
            if data == "msg":
                    self.wfile.write(someOtherData)

I want my client to be able to send the request and receive the "someOtherData" from the server:

# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((HOST, PORT))
sock.开发者_如何学Pythonsend("msg")
print sock.recv(1024)
sock.close()

But the client hangs when I try this. Where am I going wrong? Also is it necessary to know how much data the socket recv's or is there a way to just receive all the data the server writes?


As your server is doing a self.rfile.readline() it is constantly reading until it receives a newline ("\n") character. Thus your client needs to send sock.send("msg\n") for it to terminate the read command.


beside Jan answers I like to mention if you want to receive your exact message, you need to use strip to drop '\n' that you have put at the end of your string .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜