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

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

弓俊晖
2023-03-14

有人有任何示例代码来演示在java客户端接收消息socket.io?

还有,有没有从同一个套接字发送文件/二进制文件/图片的例子。io java客户端?(基本上是来自java而非javascript客户端的示例代码)

android java client的版本可以在这里获得(该版本声称它可以与socket.io 1.0及更高版本一起使用)(似乎是最新的版本)https://github.com/nkzawa/socket.io-client.java

目前的示例代码只允许我初始化连接,服务器能够获取我的传入连接事件和java套接字。io客户端能够发送基本的发射消息。然而,关于如何从服务器广播或从另一个网站用户发出的消息更新,没有简单的例子。

示例代码仅供参考:

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

谢谢你的阅读

共有3个答案

权韬
2023-03-14

经过多次尝试,以下代码对我有效:

IO.Options opts = new IO.Options();
opts.transports = new String[]{"websocket"};
Socket socket = IO.socket(SERVER_NAME, opts);

socket.on("MY MESSAGE", args -> runOnUiThread(() -> {
    Log.d("Received Message", ((JSONObject) args[0]).toString());
    JSONObject json = new JSONObject();
    
    try {
        json.put("author", "Android");
        json.put("message", "Hello!");
        socket.emit("SERVER SEND", json);
    } catch(Exception e) {
        Log.d("ERROR", e.getMessage());
    }
}));

socket.connect();

特别感谢这个回答:https://stackoverflow.com/a/31187321/6909832

狄宗清
2023-03-14

Hi希望以下实现有所帮助。下面是管理器类,它跟踪所有事件注册。传递回调,创建连接等。

public class  NetworkManager {
    private static NetworkManager mInstance;
    private Socket mSocket;
    private int RECONNECTION_ATTEMPT = 10;
    private long CONNECTION_TIMEOUT = 30000;
    private static NetworkInterface mNetworkInterface;

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

    /**
     * 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(NetworkConstant.SOCKET_CONNECTION_URL, opts);
           /*mSocket = IO.socket(NetworkConstant.SOCKET_CONNECTION_URL);
            mSocket.io().timeout(CONNECTION_TIMEOUT);
            mSocket.io().reconnection(true);
            mSocket.io().reconnectionAttempts(RECONNECTION_ATTEMPT);*/
            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) {
            mSocket.connect();
            if (mSocket.connected())
                registerConnectionAttributes();
        }
    }

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

    public void registerConnectionAttributes() {
        try {
            if(mSocket.connected()) {
                mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
                mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectionTimeOut);
                mSocket.on(Socket.EVENT_DISCONNECT, onServerDisconnect);
            }} catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void unregisterConnectionAttributes() {
        try {
            mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectionError);
            mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectionTimeOut);
            mSocket.off(Socket.EVENT_DISCONNECT, onServerDisconnect);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 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) {
            Logger.error("Response", "onConnectionError");
            mNetworkInterface.networkCallReceive(NetworkConstant.SERVER_CONNECTION_ERROR);
        }
    };

    /**
     * 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) {
            Logger.error("Response", "onConnectionTimeOut");
            mNetworkInterface.networkCallReceive(NetworkConstant.SERVER_CONNECTION_TIMEOUT);
        }
    };
    /**
     * 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) {
            Logger.error("Response", "onServerDisconnection");
            mNetworkInterface.networkCallReceive(NetworkConstant.SERVER_DISCONNECTED);
        }
    };

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

    /**
     * The purpose of this method is to unregister a method from server
     *
     * @param methodOnServer
     * @param handlerName
     */
    public void unRegisterHandler(String methodOnServer, Emitter.Listener handlerName) {
        try {
            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) {
        Logger.error("JSON ", request.toString());
        try {
            if(mSocket.connected())

            {
                mSocket.emit(methodOnServer, request);
            }
            else
                {
                    mNetworkInterface.networkCallReceive(NetworkConstant.SERVER_CONNECTION_ERROR);
                }
            } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public interface NetworkInterface {
        public void networkCallReceive(int responseType);
    }

}
戈华茂
2023-03-14

为什么我不确定这是否正是你想要的,也许你已经解决了它,不管我想回答它,因为当我在浏览我的问题的解决方案时,我在这里遇到了你的问题,但我找不到任何答案,让我失望。由于我已经解决了我的问题,我想分享一下我是如何做到的。

我的问题是我正在接收来自节点的消息。js服务器,但我只能在我的logcat中看到这条消息,我在主UI线程的android应用程序上打印这条消息时遇到了一个问题。

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

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();

我们只能从主线程更新视图。您必须将后台任务中更新ui的部分移动到主线程上。所以我们必须添加以下内容,并在其中完成我们所需的任务。

runOnUiThread(new Runnable(){

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

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

 类似资料:
  • 我最近开始学习php套接字。我想在服务器和客户端之间创建一个永久传输控制协议!但是我的PHP套接字客户端只发送和接收一条消息。我想无限期地发送和接收消息,通过一个连接。 服务器php: 客户php:

  • 假设我在MongoDB中有以下模式: 每个帖子必须有一个所有者,并且可能有许多贡献者(由所有者添加)。 当所有者或任何贡献者对post对象进行更改时,我需要将该更改实时通知给所有相关的用户(使用Socket。IO)。 但是我对如何做到这一点有一些疑问...我的意思是,我知道 Socket.IO 有一些方法可以向特定用户发出消息,但我们需要知道 SocketID。如何将用户 ID 与套接字 ID 相

  • 通常在服务器发送一些数据时发生Message事件。服务器发送到客户端的消息可以包括纯文本消息,二进制数据或图像。无论何时发送数据,都会触发函数。 此事件充当客户端对服务器的耳朵。每当服务器发送数据时,都会触发事件。 以下代码段描述了打开Web Socket协议的连接。 还需要考虑使用Web套接字可以传输哪些类型的数据。Web套接字协议支持文本和二进制数据。就Javascript而言,文本指的是字符

  • 我有1个活动和1个普通类,其中活动1接收消息,普通类发送消息。如何实施: 在活动一中。班 在Ordinary.class 如何发送空消息(1)的代码?

  • 我有套接字服务器(java桌面应用程序)正在等待从java webapp(套接字客户端)连接。通信看起来还可以,我在客户端看到来自服务器的消息,但是当我发送消息时,我在服务器端没有收到任何消息。会有什么问题呢?当我检查服务器与telnet,一切正常。下面是我的代码: 服务器: 客户: 谢谢帮忙!

  • 我在远程机器上设置了Kafka和动物园管理员。在那台机器上,我可以看到下面使用官方网站上的测试方法工作。 但是当我使用本地消费者脚本时,它就不起作用了: 我试着把它改成: 然后运行客户端使用者脚本,它会给出错误: [2017-08-11 15:49:01,591]获取相关id为3的元数据时警告错误:{listings-incoming=leader_not_available}(org.apach