Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Read string received from JavaScript WebSocket using Java InputStreamReader

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!