我开发了一个游戏,它将使用socket.io连接,我的服务器在节点js中编写,而我的android客户端使用socket.io,现在,我的问题是:
如何在不丢失与服务器的连接的情况下切换活动,我至少有4项活动,聊天,游戏视图,在线玩家列表等等。
当我打开我的应用程序时,我创建了连接,当我登录到服务器时,我想将活动切换到另一个。
有什么建议吗?
答案 0 :(得分:0)
尝试制作单例类SocketIO服务
在第一个活动初始化socketio连接以建立与服务器的连接,这里是我的示例服务类
public class SocketIOClient {
private static final String serverUrl = "http://example-socket-server.jit.su";
private static SocketIO socket;
private static SocketIOClient instance;
private static Activity act;
private static String id;
public SocketIOClient() {
}
public static void initInstance(String uid) throws MalformedURLException {
if (instance == null) {
instance = new SocketIOClient();
instance.initID(uid);
if (SocketIOClient.getSocket() == null) {
SocketIOClient.setSocket(new SocketIO());
}
SocketIOClient.connectIO();
}
}
public static void setActivity(Activity a) {
SocketIOClient.act = a;
}
public static SocketIO getSocket() {
return socket;
}
public static void setSocket(SocketIO socket) {
SocketIOClient.socket = socket;
}
public String getId() {
return id;
}
private void initID(String uid) {
if (SocketIOClient.id == null) {
SocketIOClient.id = uid;
}
}
public static void connectIO() throws MalformedURLException {
try {
SocketIO.setDefaultSSLSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SocketIOClient.getSocket().connect(serverUrl, new IOCallback() {
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
// TODO Auto-generated method stub
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
}
@Override
public void onError(SocketIOException socketIOException) {
}
@Override
public void onDisconnect() {
// TODO Auto-generated method stub
}
@Override
public void onConnect() {
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
}
});
}
public static void emit(String event, Object args)
throws MalformedURLException {
if (SocketIOClient.getSocket().isConnected() == false) {
SocketIOClient.getSocket().reconnect();
}
SocketIOClient.getSocket().emit(event, args);
}
public static void emitWithAcknowledge(String event, Object args)
throws MalformedURLException {
if (SocketIOClient.getSocket().isConnected() == false) {
SocketIOClient.getSocket().reconnect();
}
SocketIOClient.getSocket().emit(event, new IOAcknowledge() {
@Override
public void ack(Object... args) {
// TODO Auto-generated method stub
}
}, args);
}
}
在第一个活动中我输入了这段代码:
SocketIOClient.initInstance(android_id);
它是创建对象并尝试连接到服务器,如果你想要事件或某事,你可以在onConnect或onDisconnect上处理它
切换活动时,您仍然连接到服务器,如果要关闭连接,请使用以下命令:
SocketIOClient.getSocket().disconnect();