【发布时间】:2016-08-28 17:00:52
【问题描述】:
我正在尝试在 java 中运行一个简单的客户端-服务器 socket.io,但客户端无法建立连接。
我为客户端线程 https://github.com/socketio/socket.io-client-java
实现了这个 socket.io
在服务器线程上我正在使用https://github.com/mrniko/netty-socketio
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.DataListener;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class BinaryEventLauncher {
static private Socket socket;
static final int PORT = 9292;
static SocketIOServer server;
public static void main(String[] args) throws InterruptedException {
Thread ts = new Thread(new Runnable() {
@Override
public void run() {
try {
server();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
Thread tc = new Thread(new Runnable() {
@Override
public void run() {
try {
client();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
ts.start();
tc.start();
}
public static void server() throws InterruptedException, UnsupportedEncodingException {
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(PORT);
server = new SocketIOServer(config);
server.addEventListener("toServer", String.class, new DataListener<String>() {
@Override
public void onData(SocketIOClient client, String data, AckRequest ackRequest) {
client.sendEvent("toClient", "message from server");
}
});
server.start();
Thread.sleep(Integer.MAX_VALUE);
server.stop();
}
public static void client() throws URISyntaxException, InterruptedException {
IO.Options opt = new IO.Options();
opt.port = PORT;
socket = IO.socket("http://localhost", opt);
socket.on("toClient", new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println(args);
}
});
while(!socket.connected()) {
socket.connect();
Thread.sleep(100);
System.out.println(socket.connected());
}
socket.emit("toServer", "test data");//NEVER
}
}
【问题讨论】:
-
你能验证socket服务器已经启动了吗?如果是这样,服务器可能在防火墙后面吗?
-
@phhelpsiv 服务器正在运行,我使用 chrome 上的应用对其进行了测试。
-
您的端口似乎已关闭。在您提供的代码中,客户端在 9090 上侦听,服务器在 9099 上,除非这只是您帖子中的拼写错误
-
@phhelpsiv 是错字,我清除了它,并用一个也不起作用的最小代码替换了代码。