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.
source share