I'm trying to send a simple string from a Java client to a Python server.
Here's the Java client implementation:
Socket socket = new Socket(addr, PORT_NUMBER);
String message = "Hello##2##you\n"
PrintWriter outPrintWriter = new PrintWriter(socket.getOutputStream(),true);
outPrintWriter.println(answerToString);
Here's the Python server implementation:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(TIMEOUT)
s.bind(('', PORT_NUMBER))
s.listen(5)
conn, addr = s.accept()
data = conn.recv(4096)
print(data.decode())
strings_received = data.split("##")
But I get the following error while decoding:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 0: invalid start byte
I read that Java is by default encoding messages to utf-16
, so I tried with:
print(data.decode('utf-16'))
But this did not solve the issue as I obtain in output this: "Ԁ
" .
Moreover when I get to the next line I get the following error:
TypeError: a bytes-like object is required, not 'str'
How to correctly send the string from Java to Python?