0

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?

Robb1
  • 4,587
  • 6
  • 31
  • 60
  • Google that other python error. I am sure you quickly find answers for that, too. – GhostCat Jun 16 '19 at 07:27
  • @GhostCat I edited my message to make it more clear: using `decode('utf-16')` **did not solve** my issue. – Robb1 Jun 16 '19 at 07:33
  • 3
    Documentation of [`PrintWriter`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/io/PrintWriter.html#(java.io.OutputStream,boolean)): "*will convert characters into bytes using the **default** character encoding*" - no mention of UTF-16 - and reading a bit further there is a constructor that takes a [`Charset`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/nio/charset/Charset.html) to be used for encoding (the later documentation also explain which the default is) – user85421 Jun 16 '19 at 07:40
  • And as said, for the python TypeError, there are literally dozens of questions about that on SO, like: https://stackoverflow.com/questions/51940081/string-python-3-5-write-a-bytes-like-object-is-required-not-str – GhostCat Jun 16 '19 at 08:01

0 Answers0