-2

I have a string that includes a character string ="\u2663\" among others. I send the string over a socket using the printwriter and read with buffered reader:

PrintWriter out = new PrintWriter(c.clientSocket.getOutputStream(),true); out.println(string)

BufferedReader in = new BufferedReader(new InputStreamReader(mainSocket.getInputStream())); in.readLine()

When the code is run in eclipse, it renders properly but when testing it via executable jar, the unicode character above shows a "?".

I feel like this is an encoding issue but can't seem to get it to work.

dc0usa
  • 1
  • 1
  • Why doesn't it feel like a font issue? Have you checked the font you're using where you're running your app can display that symbol? – Tom Jun 16 '19 at 20:39
  • I did test that out as well but I don't think its font related because it renders when run in eclipse and because if i just set the string on the client it renders properly. The only issue is when it goes through the socket. – dc0usa Jun 16 '19 at 20:42
  • I had tried that before posting but the character is still rendering as a "?". I think \u2663 is UTF-16 but I'm not too familiar with encoding. – dc0usa Jun 16 '19 at 20:57

2 Answers2

0

I'm pretty sure I know what's going on although I still need to implement a workaround.

To use the unicode character above, I switched the eclipse text file encoding from the default (Cp1252) to UTF-8. However, when running the jar, I'm pretty sure it is using the default Cp1252. I get the same result when I change the eclipse setting back to default.

Because PrintWriter uses the default character encoding, I'm going to have to find a way to output in UTF-8 or force the JRE to override the default and use UTF-8.

dc0usa
  • 1
  • 1
  • My theory is confirmed. Running from command line with -Dfile.encoding=UTF8 works but it doesn't seem like eclipse can export a runnable jar with that setting – dc0usa Jun 16 '19 at 22:57
0

The socket is transmitting bytes, not chars. The strings you are sending are being converted to bytes and back again, but with a default encoding assumed. The reason that this has worked in your IDE and not outside it is that different default encodings are being used.

You should explicitly use a suitable encoding (say, UTF-8) on both sides of the socket, something like this

new BufferedReader(new InputStreamReader(mainSocket.getInputStream()),StandardCharsets.UTF_8)
new PrintWriter(new OutputStreamWriter(c.clientSocket.getOutputStream(),StandardCharsets.UTF_8),true)
J Banana
  • 154
  • 6
  • Thank you for the response and this is indeed the correct answer. I thought I had tried this but I must have missed a few printwriters which caused issues. Thanks! – dc0usa Jun 16 '19 at 23:06