Android和Socket.io,发送和接收数据

时间:2018-07-04 19:23:30

标签: android node.js android-studio socket.io

我可以将数据发送到server.js,并且工作正常,但是我无法从server.js接收数据。当我单击按钮server.js获取数据时,我认为Server.js发送数据,但是我的应用需要一些代码来获取数据

enter image description here

我的server.js运行良好

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.send('<h1>Hello world</h1>');
});

io.on('connection',function(socket){
    console.log('one user connected '+socket.id);



    socket.on('CHAT' , function (data) {
        console.log('======CHAT message========== ');
        console.log(data);
        socket.emit('CHAT',data);

    });

    socket.on('disconnect',function(){
        console.log('one user disconnected '+socket.id);
    });

})

http.listen(3000,function(){
    console.log('server listening on port 3000');
})

我的活动:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.Socket;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.emitter.Emitter;


public class MainActivity extends AppCompatActivity {
    public Button button;
    public TextView text;
    public EditText edit;
    private io.socket.client.Socket mSocket;

    {
        try {
            mSocket = IO.socket("http://192.168.1.4:3000");


        } catch (URISyntaxException e) {
            Log.d("myTag", e.getMessage());
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        text =  (TextView) findViewById(R.id.text);
        edit =  (EditText) findViewById(R.id.edit);
        mSocket.connect();
        text.setText("");

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                String message = edit.getText().toString().trim();
                edit.setText("");
                if (!message.isEmpty()) {
                    //send message
                    String jsonString = "{message: " + "'" + message + "'" + "}";

                    try {
                        JSONObject jsonData = new JSONObject(jsonString);
                        mSocket.emit("CHAT", jsonData);
                    } catch (JSONException e) {
                        Log.d("me", "error send message " + e.getMessage());
                    }
                }
            }
        });//button.setOnClickListener

    }//on create
}//end of class

这段代码需要这样的东西才能从Server.js中获取数据,我不知道该如何使用

mSocket.on("CHAT", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    JSONObject messageJson = new JSONObject(args[0].toString());
                    String message = messageJson.getString("message");
                    text.setText(message);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //  mMessageAdapter.notifyDataSetChanged();
                            Toast.makeText(getApplicationContext(), "Your toast message.", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

2 个答案:

答案 0 :(得分:1)

此代码运行良好。这是一个真正简单的代码,用于在nodejs和android之间发送和接收数据。

public class MainActivity extends AppCompatActivity  {

    public Button button;
    public TextView text;
    public EditText edit;
    public String message;
    private io.socket.client.Socket mSocket;

    {
        try {
            mSocket = IO.socket("http://192.168.1.4:3000");
        } catch (URISyntaxException e) {
            Log.d("myTag", e.getMessage());
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        text =  (TextView) findViewById(R.id.text);
        edit =  (EditText) findViewById(R.id.edit);
        mSocket.connect();
        text.setText("");
        setListening();

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                String message = edit.getText().toString().trim();
                edit.setText("");
                if (!message.isEmpty()) {
                    //send message
                    String jsonString = "{message: " + "'" + message + "'" + "}";

                    try {
                        JSONObject jsonData = new JSONObject(jsonString);
                        mSocket.emit("CHAT", jsonData);
                    } catch (JSONException e) {
                        Log.d("me", "error send message " + e.getMessage());
                    }
                }
            }
        });

    }//on create
        private void setListening() {
            mSocket.on("CHAT", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    try {
                        JSONObject messageJson = new JSONObject(args[0].toString());
                         message = messageJson.getString("message");
                         runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                text.setText(message);
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

}//end of class

答案 1 :(得分:1)

也许迟到了,但是您的代码有误。

socket.on('CHAT' , function (data) {
    console.log('======CHAT message========== ');
    console.log(data);
    socket.emit('CHAT',data);

});

socket.off('disconnect',function(){
    console.log('one user disconnected '+socket.id);
});

断开连接时,您正在调用socket.on而不是socket.off。我固定了上面的代码。