0

I have Java Client-Server application I built using standard java.io (Socket and ServerSocket). In both server and client, I use DataInputStream to read the message using readUTF and DataOutputStream to write the message using writeUTF. I use thread-per-connection architecture for this application.

I have an additional feature that I need to add now, which is allowing a client to have a persistent connection open to the server and always listening to what server will write. I found out, with my current thread-per-connection architecture, my application won't scale because it holds the thread when the client opens the persistent connection.

I did some research and think to refactor my server to use java.nio (SocketChannel and ServerSocketChannel). I try to make it compatible with the client (so I don't need to change the client). This is when the problem occurs because I need to change from readUTF method to using ByteBuffer class to read the message, now I got a weird character in my message.

This is my message that works before using readUTF (Server) that come from writeUTF (Client) {"command":"PUBLISH","resource":{"name":"","description":"","tags":[]}

When I sent the same message to my new server, I got this in my read method �{"command":"PUBLISH","resource":{"name":"","description":"","tags":[]}

My read method is:

else if (clientKey.isReadable()) {
    SocketChannel clientSocket = (SocketChannel) clientKey.channel();
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    clientSocket.read(buffer);
    String message = new String(buffer.array());
    Logger.debug(message);
    clientSocket.register(selector, SelectionKey.OP_WRITE);
}

This is how I write the message from client:

try (Socket echoSocket = new Socket(hostName, portNumber);
     DataOutputStream streamOut = new DataOutputStream(echoSocket.getOutputStream());) {
        streamOut.writeUTF(message.toJson());
}

toJson() is just a method to convert java object to JSON string and I use Jackson library to do that.

I have tried to remove it using regex and Normalizer library but it won't work.

Is there anyone experience the same things and solve it?

Martin Valentino
  • 1,002
  • 2
  • 11
  • 26

0 Answers0