Home > Software engineering >  Read string received from JavaScript WebSocket using Java InputStreamReader
Read string received from JavaScript WebSocket using Java InputStreamReader

Time:11-28

I am trying to read value received from JavaScript WebSocket using Java I have this JavaScript code:

const socket = new WebSocket("wss://localhost:7999"); // start

socket.addEventListener("open", (event) => {
    socket.send("Hello!");
});

socket.addEventListener("message", (event) => {
    console.log("Received message.");
});

And this Java code:

import java.io.*;
import java.net.*;

class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket s = new ServerSocket(7999);
        Socket client = s.accept();

        System.out.println("I am in!");
        InputStream inputStream = client.getInputStream();

        InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader in = new BufferedReader(reader);
        String readLine;

        while ((readLine = in.readLine()) != null) {
            System.out.println(readLine);
        }
    }
}

However, upon launching the server and client code, I am receiving this value:

I am in!
���
�.isֿ���pO?��-4/P�P����- ���Q�`�:���x���wG�Z��x��v�##�6���,� ̩�0�/̨�$�#�
�   �(�'����=<5/�
}�� localhost�

��http/1.1
3 )�� �-l-h������ۥ n�}�>�zUZ�Ğ�- 

My goal is to read the value Hello, that I have sent using socket.send. Does anyone know how to fix this problem? Thanks.

CodePudding user response:

ServerSocket is quite low level construct for handling TCP connections. Websocket even though it starts as an HTTP request it requires server to request connection upgrade, there is handshaking, then handling websocket frames, including some internal frames like ping/pong. Unless you plan to implement that entire functionality, I'd suggest you to not use raw ServerSocket but instead use a library that provides websocket support out of the box.

Some options that I could point you to are:

  • netty
  • vert.x
  • Related