TooTallNate / Java-WebSocket

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

Create and use an WebSocketClient with an URI with path. #1298

Closed raul1ro closed 1 year ago

raul1ro commented 1 year ago

I want to connect to a websocket which looks like this: wss://host.com/some/path. But the implementation of WebSocketClient ( https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/java/org/java_websocket/client/WebSocketClient.java ) is breaking my link. While I was debugging it, I saw that it is using uri.host() ( https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/java/org/java_websocket/client/WebSocketClient.java#L472 ), which result only host.com and is missing /some/path. How I can tell to WebSocketClient to use the whole URI, with path?

PhilipRoman commented 1 year ago

The code you linked only uses host() to get the address for the Socket (which doesn't know anything about HTTP or paths). Here is a simple example with server and client that connects to a URI with a path and prints it from server side:

import org.java_websocket.*;
import org.java_websocket.server.*;
import org.java_websocket.client.*;
import org.java_websocket.handshake.*;
import java.util.*;
import java.net.*;

public class EndpointServer extends WebSocketServer {
    public static void main(String... args) {
        var server = new EndpointServer();
        server.setReuseAddr(true);
        server.start();
        System.out.println("server port = " + server.getPort());

        var client = new Client("ws://localhost:" + server.getPort() + "/my/path");
        client.connect();
    }

    public void onStart() {
        // ...
    }

    public void onOpen(WebSocket socket, ClientHandshake handshake) {
        String path = URI.create(handshake.getResourceDescriptor()).getPath();
        System.out.println("path = " + path);
    }

    public void onMessage(WebSocket socket, String message) {
        // ...
    }

    public void onClose(WebSocket socket, int code, String message, boolean remote) {
        // ...
    }

    public void onError(WebSocket socket, Exception e) {
        e.printStackTrace();
    }
}

class Client extends WebSocketClient {
    public Client(String uri) {
        super(URI.create(uri));
    }
    public void onOpen(ServerHandshake handshake) {
    }

    public void onMessage(String message) {
    }

    public void onClose(int code, String message, boolean remote) {
    }

    public void onError(Exception e) {
        e.printStackTrace();
    }
}

Specifically, the code for obtaining the path on server side: URI.create(handshake.getResourceDescriptor()).getPath()

PhilipRoman commented 1 year ago

no activity, closing