简体   繁体   中英

How to send and receive whole text message (not just a part) using socket

I'm trying to create a very simple (line) server using SocketServer . I'm totally new in this are and the problem is, that I don't know how to handle recv function. I don't want to send files or something like that. Just written text from client and response from server which could be bigger (output of ipconfig etc.)

Could you give me an advice how to make that work?

When I want to request from server something longer, for example ipconfig /all , it returns a fraction of the desired output to my client and waits. If do new request as a client, it returns the rest of output from previous request.

Here is the server:

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    daemon_threads = True


class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        while 1:
            data = self.request.recv(1024)
            output = process_command(data)

            response = "{}".format(output)
            self.request.sendall(response)


if __name__ == "__main__":

    HOST, PORT = _host, int(_port)

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)

    print "Running on: %s:%s" % (HOST, PORT)
    server.serve_forever()

In the line:

data = self.request.recv(1024)

the 1024 is a limiter for the number of bits the data string can contain, so 1024 bits == 128 bytes == 128 character string. increase the number to 4096 and you will increase the limit to 512.

There are several issues.

  • The recv is a low level function and you might receive the TCP client's input in several blocks that need to be joined together. If your "protocol" is line oriented, use makefile to create a file-like object and then you can read a whole line with the readline .

  • The problem might be in the process_command , please show your code.

  • Your loop does not handle EOF (client close).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM