当前位置: 首页 > 知识库问答 >
问题:

如何设置Android Socket.io客户端?

咸弘雅
2023-03-14

在我做了插座之后。多房间聊天应用程序的IO服务器如何使用https://github.com/socketio/socket.io-client-java ? 我搜索了很多,在socket的客户端还没有找到最新的例子。对于android,大多数教程和示例都是针对带有节点的服务器端的。js。

共有2个答案

严正初
2023-03-14

它有一个在android中实现的聊天应用示例,链接如下:
https://github.com/nkzawa/socket.io-android-chat

无论如何,在android中使用socket.io,我认为最好的方法是在这样的服务中使用它:

    public class ChatService extends Service {



    public void connectSocket() {
        try {
            IO.Options options = new IO.Options();

            socket = IO.socket("http://192.168.1.1:8080", options);
            socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {

                }

            }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {

                }
            }).on("error", new Emitter.Listener() {
                @Override
                public void call(Object... args) {

                }
            });

            socket.connect();

        } catch (Exception ignored) {
        }
    }

    @Override
    public void onDestroy() {
        socket.disconnect();
        super.onDestroy();
    }

}
蒋原
2023-03-14
private static NetworkManager mInstance;
private static NetworkInterface mNetworkInterface;
private Socket mSocket;
private int RECONNECTION_ATTEMPT = 10;
private long CONNECTION_TIMEOUT = 30000;

/**
 * The purpose of this method is to get the call back for any type of connection error
 */
private Emitter.Listener testing = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Log.e("Response", args[0].toString());
    }
};

/**
 * The purpose of this method is to get the call back for any type of connection error
 */
private Emitter.Listener onConnectionError = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Log.e("Response", "onConnectionError");
        mNetworkInterface.networkCallReceive(NetworkSocketConstant.SERVER_CONNECTION_ERROR, args);
    }
};
/**
 * The purpose of this method to get the call back for connection getting timed out
 */
private Emitter.Listener onConnectionTimeOut = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Log.e("Response", "onConnectionTimeOut");
        mNetworkInterface.networkCallReceive(NetworkSocketConstant.SERVER_CONNECTION_TIMEOUT, args);
    }
};
/**
 * The purpose of this method is to receive the call back when the server get connected
 */
private Emitter.Listener onServerConnect = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Log.e("Response", "onServerConnected");
        mNetworkInterface.networkCallReceive(NetworkSocketConstant.SERVER_CONNECTED, args);
    }
};

/**
 * The purpose of this method is to receive the call back when the server get disconnected
 */
private Emitter.Listener onServerDisconnect = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Log.e("Response", "onServerDisconnection");
        mNetworkInterface.networkCallReceive(NetworkSocketConstant.SERVER_DISCONNECTED, args);
    }
};



public static NetworkManager getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new NetworkManager();
    }
    return mInstance;
}

public void registerInterface(NetworkInterface interfaces) {
    mNetworkInterface = interfaces;
}

/**
 * The purpose of this method to create the socket object
 */
public void connectToSocket() {
    try {
        IO.Options opts = new IO.Options();
        opts.timeout = CONNECTION_TIMEOUT;
        opts.reconnection = true;
        opts.reconnectionAttempts = RECONNECTION_ATTEMPT;
        opts.reconnectionDelay = 1000;
        opts.forceNew = true;
        mSocket = IO.socket(NetworkSocketConstant.SOCKET_CONNECTION_URL, opts);
        makeConnection();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


/**
 * The purpose of the method is to return the instance of socket
 *
 * @return
 */
public Socket getSocket() {
    return mSocket;
}

/**
 * The purpose of this method is to connect with the socket
 */

public void makeConnection() {
    if (mSocket != null) {
        registerConnectionAttributes();
        mSocket.connect();
    }

}

/**
 * The purpose of this method is to disconnect from the socket interface
 */
public void disconnectFromSocket() {
    unregisterConnectionAttributes();
    if (mSocket != null) {
        mSocket.disconnect();
        mSocket = null;
        mInstance = null;
        BaseApplicationActivty.networkManager = null;
    }
}

/**
 * The purpose of this method is to register default connection attributes
 */
public void registerConnectionAttributes() {
    try {
        if (mSocket != null) {
            mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
            mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectionTimeOut);
            mSocket.on(Socket.EVENT_DISCONNECT, onServerDisconnect);
            mSocket.on(Socket.EVENT_CONNECT, onServerConnect);
            registerHandlers();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

/**
 * The purpose of this method is to unregister default connection attributes
 */
public void unregisterConnectionAttributes() {
    try {
        if (mSocket != null) {
            mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectionError);
            mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectionTimeOut);
            mSocket.off(Socket.EVENT_DISCONNECT, onServerDisconnect);
            mSocket.off(Socket.EVENT_CONNECT, onServerConnect);
            unRegisterHandlers();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}


/**
 * The purpose of this method is to unregister the connection from the socket
 */
private void unRegisterHandlers() {
    try {
        //unregister your all methods here
        mSocket.off("hello", testing);
        mSocket.off("android", testing);
        mSocket.off("hello2", testing);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * The purpose of this method is to register the connection from the socket
 */
private void registerHandlers() {
    try {
        //register you all method here
        mSocket.on("hello", testing);
        mSocket.on("android", testing);
        mSocket.on("hello2", testing);
    } catch (Exception e) {
        e.printStackTrace();
    }

}


/**
 * The purpose of this method is register a single method on server
 *
 * @param methodOnServer
 * @param handlerName
 */
public void registerHandler(String methodOnServer, Emitter.Listener handlerName) {
    try {
        if (mSocket != null) {
            mSocket.on(methodOnServer, handlerName);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * The purpose of this method is to unregister a single method from server
 *
 * @param methodOnServer
 * @param handlerName
 */
public void unRegisterHandler(String methodOnServer, Emitter.Listener handlerName) {
    try {
        if (mSocket != null) {
            mSocket.off(methodOnServer, handlerName);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * The purpose of this method is to send the data to the server
 *
 * @param methodOnServer
 * @param request
 */
public void sendDataToServer(String methodOnServer, JsonObject request) {

    try {
        if (mSocket != null && mSocket.connected()) {
            Log.e("JSON ", request.toString());
            mSocket.emit(methodOnServer, request);
        } else {
            mNetworkInterface.networkCallReceive(NetworkSocketConstant.SERVER_CONNECTION_ERROR);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public interface NetworkInterface {
    void networkCallReceive(int responseType, Object... args);
}

公共抽象类BaseActive扩展AppCompatActive{

/**
 * The purpose of this method is to receive the callback from the server
 */
private NetworkManager.NetworkInterface networkInterface = new NetworkManager.NetworkInterface() {
    @Override
    public void networkCallReceive(int responseType, Object... args) {
        switch (responseType) {
            case NetworkSocketConstant.SERVER_CONNECTION_TIMEOUT:
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(BaseActivity.this, getResources().getString(R.string.sorry_no_internet_connection), Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case NetworkSocketConstant.SERVER_CONNECTION_ERROR:
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(BaseActivity.this, (getResources().getString(R.string.connection_error)), Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case NetworkSocketConstant.SERVER_CONNECTED:
                SharedPreferenceUtility sharedPreferenceUtility = new SharedPreferenceUtility(BaseActivity.this);
                if (sharedPreferenceUtility.getUserId() != null && !sharedPreferenceUtility.getUserId().isEmpty()) {
                     SocketEmitter.emitSocketConnectionService(BaseActivity.this);
                    SocketEmitter.emitTesting(BaseActivity.this, "android");
                }
                break;
            case NetworkSocketConstant.SERVER_DISCONNECTED:
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(BaseActivity.this, getResources().getString(R.string.disconnected), Toast.LENGTH_SHORT).show();
                    }
                });
                break;
    }
};


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    socketInit();

}

// initialization socket
private void socketInit() {
    if (BaseApplicationActivty.networkManager == null) {
        BaseApplicationActivty.networkManager = NetworkManager.getInstance(getApplicationContext());
        BaseApplicationActivty.networkManager.registerInterface(networkInterface);
        BaseApplicationActivty.networkManager.connectToSocket();
    } else {
        BaseApplicationActivty.networkManager.registerInterface(networkInterface);
    }
}

/**
 * This Method must call all ui fragment/activity using Rx subs.
 */
protected abstract void onPermissionResult(int requestCode, boolean isPermissionGranted);

/**
 * This Method must call all ui fragment/activity using Rx subs.
 */
protected abstract void onSocketApiResult(int requestCode, Object... args);

/**
 * Request For Permission of particular type.
 *
 * @param requestCode
 * @param permission
 * @return
 */
public boolean requestPermission(int requestCode, String... permission) {

    boolean isAlreadyGranted = false;

    isAlreadyGranted = checkPermission(permission);

    if (!isAlreadyGranted)
        ActivityCompat.requestPermissions(this, permission, requestCode);

    return isAlreadyGranted;

}

protected boolean checkPermission(String[] permission) {

    boolean isPermission = true;
    for (String s : permission)
        isPermission = isPermission && ContextCompat.checkSelfPermission(this, s) == PackageManager.PERMISSION_GRANTED;

    return isPermission;
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        onPermissionResult(requestCode, true);

    } else {

        onPermissionResult(requestCode, false);
        Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_LONG).show();

    }

}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

}

 类似资料:
  • 问题内容: 我有几个关于客户端节点的Elasticsearch问题: 我可以说:任何节点只要打开HTTP端口,我都可以将它们视为“客户端”节点,因为我们可以通过该节点进行搜索/索引。 实际上,当和时,我们将节点视为客户端节点,如果我设置了10个客户端节点,是否需要在客户端进行路由,这意味着如果我在代码 中将clientOne:9200 指定为ES门户,则 clientOne会 转发其他HTTP请求

  • 自定义成菜单 说明: 1)启用该功能后,直播客户端可以通过自定义菜单的方式加载用户自定义的网页,方便结合自身业务进行交互操作(客户端5.0.0以上版本支持) 问卷设置 说明: 1)在直播管理页面点击 “问卷设置”,启用该功能后,直播客户端可以通过接口请求的方式将用户问卷库中的问卷导入到客户端中使用 2)关于问卷设置的具体功能及使用方法,请参考:问卷接口开发指南 菜单设置 说明: 1)支持对客户端的

  • 我使用使用SSL的安全通道通过JMS与Weblogic IBM Webpsphere MQ建立了连接。我在Weblogic上的应用程序收到了来自MQ的消息。正在将应答发送到应答队列。响应头存在MQMD,它填充java。在参数持久化JMS发送值“1”中。其他系统需要在持久化时接收值“0”。如何将此参数设置为java?我猜这个参数是javax。jms。deliverymode。但我不知道怎么设置。 无

  • 我试图创建一个AWS客户端为IOT以下这篇文章:我如何才能发布到MQTT主题在亚马逊AWS Lambda函数? 但是,我需要设置一个配置文件,以便从我的文件中选择正确的凭据。 描述如何做到这一点(使用boto3连接到CloudFront时如何选择AWS配置文件)的文章使用了,而不是创建。但是,不是您可以从会话中获得的“资源”。 当我尝试上述操作时,我得到了错误: 我们已经达到了完全的第22条军规。

  • 我们能以编程方式获取HTTPClientPolicy对象吗?或者我们必须在传递给template.send()的Camel URI中引用它,例如:

  • 由于我需要使用一些旧服务器,并且由于已从Java8中删除,因此我需要重新启用一些基于RC4的密码。如发行说明中所述,我们必须使用。由于我使用的是Apache HTTP客户端,因此无法找到执行此操作的方法。提前感谢!(我还发现了相当多的半挂车问题,但没有答案,所以想发布一个新的)