且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Socket.io android java客户端接收消息和发送文件示例

更新时间:2022-10-24 22:17:41

我不确定这是否正是您正在寻找的,并且可能您已经解决了它,不管我愿意当我浏览我的问题的解决方案时回答它,我在这里遇到了你的问题,但我找不到任何答案,让我很失望.由于我已经解决了我的问题,我想分享我是如何做到的.

我的问题是我正在从 node.js 服务器接收消息,但我只能在我的 logcat 中看到该消息,而且我真的无法在主 UI 线程的 Android 应用程序上打印该消息.>

比方说,我们将在列表视图中显示从服务器收到的消息.

尝试{socket = IO.socket("http://192.168.1.10:3000");} catch (URISyntaxException e) {e.printStackTrace();}socket.on(Socket.EVENT_CONNECT, 新的 Emitter.Listener() {@覆盖公共无效调用(对象...参数){Log.d("ActivityName:", "socket已连接");//将您想要的任何内容发送到服务器socket.emit("登录", 一些);//socket.disconnect();}//这是来自服务器的发射}).on("someFunction", new Emitter.Listener() {@覆盖公共无效调用(对象...参数){//这个 argas[0] 可以是你从服务器发送的任何类型JSONArray obj = (JSONArray) args[0];字符串消息 = obj.toString();//如果要更改 UI 线程中的某些内容,则需要 runOnUiThreadrunOnUiThread(new Runnable() {公共无效运行(){//做一点事//mListData 是数组适配器mListData.add("Serversays" + " : " + " " + message);mListData.notifyDataSetChanged();lvList.setSelection(mListData.getCount() -1);}});}}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {@覆盖公共无效调用(对象...参数){Log.d("ActivityName:", "socket 断开连接");}});套接字连接();

我们只能从主线程更新视图.您必须将更新 ui 的后台任务部分移动到主线程上.因此我们必须添加以下内容并在其中执行我们需要的任务.

runOnUiThread(new Runnable(){@覆盖公共无效运行(){//做一点事}}

希望它能为某人节省时间.

Does anyone have any sample code which demonstrates receiving messages on the java client side for socket.io?

Also, is there any example on sending a file/binary/picture over from the same socket.io java client? (basically sample code from java instead of javascript client)

The version of android java client can be acquired here (this version claim that it can be used with socket.io 1.0 and later) (seems to be the most updated version) https://github.com/nkzawa/socket.io-client.java

Currently the sample code which only allows me to initialize a connection, the server is able to get my incoming connection event and the java socket.io client is able to send out a basic emit message. However, there is no plain simple examples on how to acquire a message update from a server broadcast or emits from another website user.

Sample code just for reference:

package com.sample.d10132014a;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.github.nkzawa.socketio.client.*; // java socket io client
import com.github.nkzawa.socketio.client.Socket;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.engineio.client.*; // java engine io client
import com.github.nkzawa.engineio.client.transports.*;


public class MainActivity extends Activity {

    public static String internalPath; // internal storage path
    public static String fileName; // the file name
    private Socket socket; // socket object
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        try 
        {
            socket = IO.socket("http://YOURSERVERIP:3000");
            socket.connect();  // initiate connection to socket server
            socket.emit("chat message",  "From Android to server: 1st outgoing message");
        } 
        catch (URISyntaxException e) 
        {
            e.printStackTrace();
        }


      socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() 
      {

          @Override
          public void call(Object... args) {
              Log.d("socketio", "socket connected");
              socket.emit("chat message", "even connect: message sent from android to socketio server");
              //socket.disconnect(); // why is there a disconnect here?
          }
      }).on("chat message", new Emitter.Listener() {

        @Override
        public void call(Object... arg0) {
            // TODO Auto-generated method stub
            JSONObject obj = (JSONObject)arg0[0];
            Log.d("socketio", "message back: "+obj.toString());
            Log.d("socketio", "incomming chat message: " + obj.toString() + arg0 + arg0[0] + arg0[1]); // trying to test which variable holds the message
        }
        }).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {

            @Override
            public void call(Object... arg0) {
                // TODO Auto-generated method stub
                Log.d("socketio", "socket event message" + arg0);
                socket.emit("chat message", "android to server from event message");
            }
        });




      // 2nd segment test without connecting to 1 long method
      socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() 
      {
        @Override
        public void call(Object... arg0) {
            // TODO Auto-generated method stub
            Log.d("socketio", "socket event connect error");
            socket.emit("chat message",  "android to server: socket event connect error");
        }
      });

      socket.on(Socket.EVENT_MESSAGE, new Emitter.Listener() {

        @Override
        public void call(Object... arg0) {
            // TODO Auto-generated method stub
            Log.d("socketio", "socket event message" + arg0);
            socket.emit("chat message", "android to server from event message");
        }
    });
    setContentView(R.layout.activity_main);


    } // ending onCreate method

} // ending class

Thanks for reading

Hy I am not sure if this is exactly what u are looking for, and there might be a chance that you have already solved it, regardless i would like to answer it as when i was browsing for a solution to my problem, i came across your question here but i couldnot find any answer, left me disappointed. As i have already solved my problem, i would like to share how i did it.

My problem was i was receiving the message from the node.js server but i could only see that message in my logcat and i was really having a problem to print that message on my android application in the main UI thread.

Lets say, we would show the message received from the server in the list view.

try {
        socket = IO.socket("http://192.168.1.10:3000");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            Log.d("ActivityName: ", "socket connected");

            // emit anything you want here to the server
            socket.emit("login", some);
            //socket.disconnect();
        }

   // this is the emit from the server
    }).on("someFunction", new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            // this argas[0] can have any type you send from the server
            JSONArray obj = (JSONArray) args[0];
              String message = obj.toString();

            // runOnUiThread is needed if you want to change something in the UI thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // do something
                    //mListData is the array adapter
                        mListData.add("Serversays" + " : " + " " + message);
                        mListData.notifyDataSetChanged();
                        lvList.setSelection(mListData.getCount() -1);
                }
            });
        }
    }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            Log.d("ActivityName: ", "socket disconnected");
        }

    });
    socket.connect();

we can update views only from main thread. You have to move the portion of the background task that updates the ui onto the main thread.So we have to add the following and do our required task in there.

runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
//do something
}
}

Hope it will save time for someone.