Skip to content Skip to sidebar Skip to footer

Python Socket Recv From Java Client

I have a problem with a simple python tcp server (I'm using SocketServer class) that have to receive data from a java client. Here the server side code: class ServerRequestHandler

Solution 1:

the recv doesn't have to read 4 bytes, it just grabs whatever is there up to a max of four bytes. Since, as you said, you can call recv(1) 4 times. you can do this

defrecvall(sock, size):
    msg = ''whilelen(msg) < size:
        part = sock.recv(size-len(msg))
        if part == '': 
            break# the connection is closed
        msg += part
    return msg

this will repeatedly call recv on sock until size bytes are received. if part == '' the socket is closed so it will return whatever was there before the close

so change

requestCode = struct.unpack('>i', self.request.recv(4))[0]

to

requestCode = struct.unpack('>i', recvall(self.request, 4))[0]

I'd suggest making recvall a method of your class to make things cleaner.


this is a modification of a method from the safe socket class defined here: http://docs.python.org/howto/sockets.html

Solution 2:

recv(4) will read a maximum of 4 bytes. See the docs: http://docs.python.org/library/socket.html . I think making a simple buffered reader function is a perfectly acceptable solution here.

Solution 3:

Maybe you could use something from io module? BufferedRWPair for example.

Post a Comment for "Python Socket Recv From Java Client"