I'm sending int
by using DataOutputStream
to Python via a socket but the data I receive at the Python part occasionally gets corrupted and I get the following error:
unpack requires a string argument of length 4
Not to mention that I run the Java part repeatedly. I have no idea why this happens. Please help.
Here is the Java part:
public static void main(String[] args) {
Socket sock = null;
DataOutputStream out = null;
try {
sock = new Socket("192.168.0.104", 1234);
out = new DataOutputStream(sock.getOutputStream());
out.writeInt(2);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is the Python part:
import socket
import struct
host = '192.168.0.104'
port = 1234
backlog = 5
size = 4
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
unpacked = int(struct.unpack('>i', data)[0])
if data:
print unpacked
client.close()
Here is the output:
2
2
2
Traceback (most recent call last):
File "test_socket1.py", line 20, in <module>
unpacked = int(struct.unpack('>i', data)[0])
struct.error: unpack requires a string argument of length 4