简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM