Socket.io android java客户端接收消息和发送文件示例 [英] Socket.io android java client receiving messages and sending file example

查看:83
本文介绍了Socket.io android java客户端接收消息和发送文件示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

另外,有没有关于从同一个 socket.io java 客户端发送文件/二进制文件/图片的例子?(基本上来自java而不是javascript客户端的示例代码)

android java客户端的版本可以在这里获取(这个版本号称可以和socket.io 1.0及以后的版本一起使用)(好像是最新的版本)https://github.com/nkzawa/socket.io-client.java

目前的示例代码只允许我初始化连接,服务器能够获取我的传入连接事件并且 java socket.io 客户端能够发出基本的发射消息.然而,没有简单的例子来说明如何从服务器广播或其他网站用户发出的消息获取更新.

示例代码仅供参考:

package com.sample.d10132014a;导入 java.io.BufferedReader;导入 java.io.FileInputStream;导入 java.io.FileNotFoundException;导入 java.io.InputStream;导入 java.io.InputStreamReader;导入 java.net.URISyntaxException;导入 org.json.JSONException;导入 org.json.JSONObject;导入 android.app.Activity;导入 android.os.Bundle;导入 android.util.Log;导入 android.view.Menu;导入 android.view.MenuItem;导入 com.github.nkzawa.socketio.client.*;//java socket io客户端导入 com.github.nkzawa.socketio.client.Socket;导入 com.github.nkzawa.emitter.Emitter;导入 com.github.nkzawa.engineio.client.*;//java引擎io客户端导入 com.github.nkzawa.engineio.client.transsports.*;公共类 MainActivity 扩展 Activity {公共静态字符串内部路径;//内部存储路径公共静态字符串文件名;//文件名私有 Socket 套接字;//套接字对象@覆盖protected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);尝试{socket = IO.socket("http://YOURSERVERIP:3000");套接字连接();//启动到socket服务器的连接socket.emit("聊天消息", "从安卓到服务器:第一条传出消息");}捕获(URISyntaxException e){e.printStackTrace();}socket.on(Socket.EVENT_CONNECT, new Emitter.Listener(){@覆盖公共无效调用(对象...参数){Log.d("socketio", "socket已连接");socket.emit("chat message", "even connect: 消息从android发送到socketio服务器");//socket.disconnect();//为什么这里有断开连接?}}).on("聊天消息", new Emitter.Listener() {@覆盖公共无效调用(对象... arg0){//TODO 自动生成的方法存根JSONObject obj = (JSONObject)arg0[0];Log.d("socketio", "消息回复:"+obj.toString());Log.d("socketio", "收到聊天消息:" + obj.toString() + arg0 + arg0[0] + arg0[1]);//尝试测试哪个变量保存消息}}).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {@覆盖公共无效调用(对象... arg0){//TODO 自动生成的方法存根Log.d("socketio", "socket 事件消息" + arg0);socket.emit("聊天消息", "android 从事件消息到服务器");}});//没有连接到 1 个长方法的第 2 段测试socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener(){@覆盖公共无效调用(对象... arg0){//TODO 自动生成的方法存根Log.d("socketio", "socket 事件连接错误");socket.emit("chat message", "android to server: socket event connect error");}});socket.on(Socket.EVENT_MESSAGE, new Emitter.Listener() {@覆盖公共无效调用(对象... arg0){//TODO 自动生成的方法存根Log.d("socketio", "socket 事件消息" + arg0);socket.emit("聊天消息", "android 从事件消息到服务器");}});setContentView(R.layout.activity_main);}//结束onCreate方法}//结束类

感谢阅读

解决方案

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

我的问题是我正在从 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.

这篇关于Socket.io android java客户端接收消息和发送文件示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆