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

161
Views
Trying to connect to java web socket from js backen

I am tryin to establish connection from js websocket to java application to send and receive messages. I tried different things but after all, my frontend writes this in console -

> client.js:13 WebSocket connection to 'ws://localhost:8081/websocket'
> failed:  openWebSocket @ client.js:13

I don't know how to configure my backend. Please help me!

My code in Java:

@ServerEndpoint("localhost:8081/websocket")
public class MessageEndpoint {
    static Session session;
    @OnOpen
    public void openWebSocket(@PathParam("token") String token, Session session){
        this.session=session;

        System.out.println("Opened a websocket for user"+token);
    }
    @OnMessage
    public void onMessage(Session session, String message){
        System.out.println(message);
    }
}

And code in JS:

function openWebSocket(token) {
  $("#loginCon").hide(); 
  curCon = $("#initCon");
  curCon.show();
  ws = new WebSocket("ws://localhost:8081/websocket");
  ws.onopen = function() {
    console.log('Web socket opened');
  }
  ws.onclose = function() {
    console.log('Web socket closed');
    $("#loginCon").show();
    curCon.hide();
  }
  ws.onmessage = function(msg) {
    console.log("<< " + msg.data);
    var m = JSON.parse(msg.data);
    if (m.type === 'state') {
      updateState(m);
    } else if (m.type === 'response') {
      var h = requestHandlers.get(m.requestId);
      requestHandlers.delete(m.requestId);
      if (m.error) {
        if (h.fail) {
          h.fail(m.errorMessage);
        }
      } else if (h.success) {
        h.success(m.response);
      }
    }
  }
}
about 4 years ago · Juan Pablo Isaza
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!