0

For a chat app in Java/Swing over Java sockets, is this enough to ensure text is encoded/displayed properly while avoiding platform-specific encoding? (the client may run on Windows, Linux, Mac)

//sending
bytes chatMsgAsBytes = textField.getText().getBytes("UTF-8");
socketOutputStream.write(chatMsgAsBytes);

.

//receiving
byte[] bytes = ...
socketInputStream.read(bytes);
textField.setText( new String(bytes,"UTF-8"));

I checked this, but is there anything else major to consider to avoid issues with platform-specific encoding when sending bytes over the network?

Community
  • 1
  • 1
raffian
  • 31,267
  • 26
  • 103
  • 174
  • This should work for any system, regardless of it's default encoding. – Cruncher Nov 01 '13 at 17:25
  • 1
    You could also use [`DataOutputStream`](http://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html)/[`DataInputStream`](http://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html) which have encoding safe `String` interchange methods built in. – Boris the Spider Nov 01 '13 at 17:33

1 Answers1

1

I have used ObjectOutputStream and ObjectInputStream to achive this.

Socket:

  Socket cliente = new Socket(host, port);
  ObjectOutputStream oos = new ObjectOutputStream(cliente.getOutputStream());
  ObjectInputStream ois= new ObjectInputStream(cliente.getInputStream());

To send:

  String message="Hi";
  oos.writeObject(m);
  oos.flush();

To receive:

 String msg = (String)ois.readObject();
nashuald
  • 805
  • 3
  • 14
  • 31