Okay! It works perfect now that I GET the Cookie first. It was pretty easy using the OkHttp3 library, which was already a dependent of SocketIO, so I didn't have to add any more dependencies.
I'm not sure if this is useful to anyone else, but here is my test app.
package com.radiofreederp.nodebbapp;
import io.socket.client.Ack;
import io.socket.client.IO;
import io.socket.client.Manager;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import io.socket.engineio.client.Transport;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class NodeBBApp {
private String url;
private OkHttpClient client = new OkHttpClient();
private String cookie;
private Socket socket;
NodeBBApp(String url) {
this.url = url;
}
private void getCookie() throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
cookie = response.headers().get("Set-Cookie");
}
private void connectSocket() throws URISyntaxException {
socket = IO.socket(url);
// Send the session cookie with requests.
socket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
@Override
public void call(Object... args) {
Transport transport = (Transport)args[0];
transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
@Override
public void call(Object... args) {
@SuppressWarnings("unchecked")
Map<String, List<String>> headers = (Map<String, List<String>>)args[0];
headers.put("Cookie", Arrays.asList(cookie));
}
});
}
});
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... objects) {
JSONObject data = new JSONObject();
try {
data.put("tid", 45);
data.put("after", 1);
data.put("direction", 1);
} catch (JSONException e) {
e.printStackTrace();
}
socket.emit("topics.loadMore", data, new Ack() {
@Override
public void call(Object... objects) {
System.out.println("Response:");
if (objects.length == 2 && objects[0] == null) {
JSONObject data = (JSONObject)objects[1];
try {
JSONArray posts = data.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
System.out.println(((JSONObject)posts.get(i)).get("content"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
socket.close();
}
});
}
});
socket.connect();
}
public static void main(String [] args)
{
NodeBBApp app = new NodeBBApp("http://www.yaricraft.com/");
try {
app.getCookie();
app.connectSocket();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}