0

So I have this java websocket server, that is on a separate machine, with no firewall and opened ports:

ServerSocket serverSocket = new ServerSocket(23547);
        Thread serverThread = new Thread(() -> {
            while(true) {
                try {
                    Socket connection = serverSocket.accept();

                    try (
                            BufferedReader serverReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                            Writer serverWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
                    ) {
                        serverWriter.write("hello, " + serverReader.readLine() + "\n");
                        serverWriter.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Throwable t) {
                    t.printStackTrace();
                    throw t;
                }
            }
        });
        serverThread.setDaemon(true);
        serverThread.start();

And when trying to listen with javascript, I get this "WebSocket connection to 'ws://xxx.xxx.xxx.xx:23547/' failed" instantly, while when trying to access to other random ports it takes 5/8 seconds before throwing an error.

JavaScript code used to connect to the WS:

var exampleSocket = new WebSocket("ws://xxx.xxx.xxx.xx:23547");

Thank you !

Ubroute
  • 3
  • 1
  • 1
    [TCP sockets are not WebSockets](https://stackoverflow.com/questions/2681267/what-is-the-fundamental-difference-between-websockets-and-pure-tcp). – Take-Some-Bytes Aug 14 '21 at 20:24

1 Answers1

0

The ServerSocket class doesn't create a WebSocket, but a TCP socket. WebSocket is an additional layer with its own protocol requirements.

MDN provides a tutorial on Writing a WebSocket server in Java using a ServerSocket.

If you're running in a JavaEE 7 compatible container you can use the Java API for WebSocket. Oracle provides a tutorial called "Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5".

There are also numerous third-party libraries available for implementing WebSocket servers. Here are a few examples:

Tim Moore
  • 8,958
  • 2
  • 23
  • 34