TooTallNate / Java-WebSocket

A barebones WebSocket client and server implementation written in 100% Java.
http://tootallnate.github.io/Java-WebSocket
MIT License
10.33k stars 2.56k forks source link

Cannot connect to ws server opened by java-websocket #1396

Closed NriotHrreion closed 3 months ago

NriotHrreion commented 3 months ago

Describe the bug

I opened a ws server on port 6000 with java-websocket, and was trying to connect it with the WebSocket object in javascript in browser. And I was getting the error WebSocket connection to 'ws://localhost:6000/' failed

Example application to reproduce the issue

My java code (I have called the start() method in other place):

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

import java.net.InetSocketAddress;

public class Server extends WebSocketServer {
    public static final int port = 6000;

    public Server() {
        super(new InetSocketAddress("localhost", port));
    }

    @Override
    public void onOpen(WebSocket ws, ClientHandshake handshake) {
        System.out.println("Connected!");
        ws.send("Welcome");
        broadcast("new connection: "+ handshake.getResourceDescriptor());
    }

    @Override
    public void onClose(WebSocket ws, int code, String reason, boolean remote) {
        System.out.println("Disconnected!");
    }

    @Override
    public void onMessage(WebSocket ws, String message) {
        broadcast(message);
        System.out.println(ws +": "+ message);
    }

    @Override
    public void onError(WebSocket ws, Exception e) {
        e.printStackTrace();
    }

    @Override
    public void onStart() {
        // This line "Server is ready on the port" is printed in command line
        System.out.println("Server is ready on the port "+ getPort() +"!");
    }
}

My javascript code:

new WebSocket("ws://localhost:6000");

Environment:

NriotHrreion commented 3 months ago

solved