I'm trying to use socket.io for a work project. In order to learn how this library works, I want to setup a test server and client in which I can run some code.
For now, I have set up a working JavaScript server as per the example listed here: https://socket.io/docs/v4/.
import { Server } from "socket.io";
const io = new Server(3000);
io.on("connection", (socket) => {
console.log("connection");
// send a message to the client
socket.emit("hello from server", 1, "2", { 3: Buffer.from([4]) });
// receive a message from the client
socket.on("hello from client", (...args) => {
console.log("client says hi");
});
});
When I setup the client which is also shown on the website above, I see the output of my console.log
function. Here's the working JavaScript client that I'm using:
import { io } from "socket.io-client";
const socket = io("ws://localhost:3000");
// send a message to the server
socket.emit("hello from client", 5, "6", { 7: Uint8Array.from([8]) });
// receive a message from the server
socket.on("hello from server", (...args) => {
// ...
});
However, I need to run the client using Java. Here's my problem, and probably where I'm missing some fundamental insight, when I try to run a Java client with the above JavaScript server, I see no output whatsoever. I'm using https://github.com/socketio/socket.io-client-java and this is how I defined my client:
// package + imports
public class Main
{
public static void main(String[] args)
{
URI uri = URI.create("http://localhost:3000");
IO.Options options = IO.Options.builder().build();
Socket socket = IO.socket(uri, options);
socket.emit("hello from client", "world");
}
}
I've also tried URI uri = URI.create("ws://localhost:3000");
because the documentation says ws and http are interchangeable, but to no avail.
Why is my server not outputting anything when I run my Java class, and how do fix it
I fixed the problem by adding socket.open()
after Socket socket = IO.socket(uri, options);
in my Java client.
I didn't see this posted in the documentation so I opened a PR to add it https://github.com/socketio/socket.io-client-java/pull/732