Python socket recv from java client

I have a problem with a simple python tcp server (I use the SocketServer class), which should receive data from a java client.

Here is the server side code:

 class ServerRequestHandler(SocketServer.BaseRequestHandler): [...] def handle(self): requestCode = struct.unpack('>i', self.request.recv(4))[0] [...] [...] 

There is a client here:

 addr = InetAddress.getByName(hostname); SocketAddress sockaddr = new InetSocketAddress(addr, port); clientSocket = new Socket(); clientSocket.connect(sockaddr, timeoutMs); clientSocketDataOutputStream = new DataOutputStream(clientSocket.getOutputStream()); int requestCode = 1; clientSocketDataOutputStream.writeInt(requestCode); clientSocketDataOutputStream.flush(); 

I start a Python server and then try to execute a client that needs to send an integer to the server.

On the server side, Python throws an exception because the recv(4) function does not read 4 bytes, it returns only one byte.

My java client sends 4 bytes correctly, if I try to call recv(1) 4 times, it will read 4 bytes correctly.

I tried to write a Python client that does the same operation with my java client, in which case the recv(4) server works fine.

How to solve this problem? I decided to implement a simple python buffered reader function that reads from the byte of the socket by byte, but I'm sure there is a more reasonable solution.

+4
source share
3 answers

recv does not have to read 4 bytes, it just captures everything that can be up to four bytes. Because, as you said, you can call recv (1) 4 times. You can do it

 def recvall(sock, size): msg = '' while len(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 that it returns everything that was before closing

so change

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

to

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

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


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

+5
source

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

0
source

Perhaps you could use something from the io module? BufferedRWPair , for example.

0
source

All Articles