Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

398
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda