Android App Connecting to Node.js server using Socket.io

后端 未结 4 481
一生所求
一生所求 2020-12-07 15:15

I\'m having trouble getting my Android app to connect to a socket.io chat server. I\'m using socket.io-java-client created by Gottox which can be found here: https://github.

4条回答
  •  一个人的身影
    2020-12-07 15:38

    Puma has already answered on how you can implement a socket connection using SocketIO. This has nothing new to contribute. Yet, it is an attempt to help fellow newbies, as also introduce the implementation of Socket.io's java library.

    Socket.IO has its own java implementation on Github, which you can follow along to create a socket application for Android/Java.

    Android side:

    Include this in your build gradle

    compile ('io.socket:socket.io-client:0.8.3') {
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    

    Provide Permission in your app:

    
    

    Android Code: The structure of code is similar to how you would code in Node. The message in socket.on is similar to node's socket.on('message', ...)

    import io.socket.client.Socket;
    import io.socket.client.IO;
    import io.socket.emitter.Emitter;
    
    final Socket socket;
    try{
    socket = IO.socket("http://192.168.1.1:8080");
    
    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
    
        @Override
        public void call(Object... args) {
            socket.emit("message", "hi");
            socket.disconnect();
        }
    
    }).on("message", new Emitter.Listener() {
            //message is the keyword for communication exchanges
        @Override
        public void call(Object... args) {
            socket.emit("message", "hi");
        }
    
    }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
    
        @Override
        public void call(Object... args) {}
    
    });
        socket.connect();
    
    }
    catch(Exception e){
        
    }
    

    Node.js side

    Create normal sockets using socket.io

提交回复
热议问题