Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

382
Visualizações
Can't connect client (Javascript) to existing socket server

I have an existing socket server that listens on port 6868. It is written in Java.

I need to connect a client to the server. The client is coded in Javascript in my React app.

I have tried just about every possible combination of tutorials I have found on the internet but I still can't get the client to connect.

import * as io from "socket.io-client";

export default () => {
  // eslint-disable-next-line no-restricted-globals
  self.onmessage = (message) => {
    const data = message.data;
      try {
      var socket = io("http://localhost:6868/");
    } catch (error) {
      console.log("do nothing: " + error);
    }
  };
};

No matter what, I get the same error: ReferenceError: socket_io_client__WEBPACK_IMPORTED_MODULE_0___default is not defined.

This is the version I am using as seen in package.json: "socket.io-client": "^4.4.0"

I installed it with this command: npm i socket.io-client

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Turns out that socket.io can't be used to connect to the ServerSocket that I have in Java. To fix this, I changed ServerSocket to be a WebSocketServer.

Here is all of the code needed to make Java WebSocket connect with JavaScript client:

WebsocketServer.java

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Set;

public class WebsocketServer extends WebSocketServer {

    private static int TCP_PORT = 6868;

    private static Set<WebSocket> conns;


    public WebsocketServer() {
        super(new InetSocketAddress(TCP_PORT));
        conns = new HashSet<>();
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conns.add(conn);
        conn.send("hello!!");
        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        conns.remove(conn);
        System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Message from client: " + message);
        for (WebSocket sock : conns) {
            sock.send("SENDING BACK" + message);
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //ex.printStackTrace();
        if (conn != null) {
            conns.remove(conn);
            // do some thing if required
        }
        System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    public static Set<WebSocket> getConns() {
        return conns;
    }
}

And launch the server from main() with new WebsocketServer().start();

client.js

    var connection = new WebSocket("ws://127.0.0.1:6868");

    connection.onopen = function () {
      console.log("Connected!");
      connection.send("Ping"); // Send the message 'Ping' to the server
    };

    // Log errors
    connection.onerror = function (error) {
      console.log("WebSocket Error " + error);
    };

    // Log messages from the server
    connection.onmessage = function (e) {
      console.log("Server: " + e.data);
    };

And the dependency for the Java Web Socket:

    <dependency>
        <groupId>
            org.java-websocket
        </groupId>
        <artifactId>
            Java-WebSocket
        </artifactId>
        <version>
            1.3.0
        </version>
    </dependency>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda