raffian
raffian

Reputation: 32086

How to safely encode Strings as bytes over sockets for chat app

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?

Upvotes: 0

Views: 295

Answers (1)

nashuald
nashuald

Reputation: 825

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();

Upvotes: 1

Related Questions