【问题标题】:Android and Socket.io , send and receive dataAndroid 和 Socket.io ,发送和接收数据
【发布时间】:2018-12-13 06:12:06
【问题描述】:

我可以向 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();
                }
            }
        });

【问题讨论】:

  • 有什么问题?这就是你收到的方式。我没有发现您的代码有任何问题。
  • Brother Marcos 我无法从 server.js 接收数据。我可以将数据从 android 发送到 server.js,但我无法从 server.js 获得任何东西
  • “我无法接收”并没有删减它。你有什么错误吗?你在哪里有你的mSocket.on("CHAT"
  • 您是否尝试在mSocket.on("CHAT") 侦听器中放置日志?看看它是否到达那里?

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


【解决方案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

【讨论】:

  • 嘿@Moh_beh 当我断开套接字并重新打开主要活动,然后尝试使用 setListening() 多次调用该方法获取消息时。我多次得到同一个对象。你能帮帮我吗?
  • 嘿@Moh_ben 我尝试了完全相同的代码,但对于本地主机和从模拟器运行的应用程序,它不起作用。你知道可能是什么原因吗?问候
【解决方案2】:

也许迟到了,但你的代码有错误。

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。我在上面的代码中修复了。

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多