当有数据可以在socket中读取时,android中是否有任何回调机制 [英] Is there any callback mechanism in android when there is data available to read in socket

查看:30
本文介绍了当有数据可以在socket中读取时,android中是否有任何回调机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我熟悉 c、iOS 环境中的 socket 编程.但是现在尝试通过 socket 连接我的 android 和我的远程服务器...作为一个启动,我用 C 编写了一个简单的服务器程序并运行它我的桌面耐心地等待连接请求,接受连接,然后等待一些请求字符串,并在获取请求字符串时返回一些响应字符串,然后再次等待下一个请求并继续..你明白了..

Well I am familiar with socket programming in c, iOS environment..But now trying to connect my android and my remote server via sockets...As a start up, I wrote a simple server program in C and ran it on my desktop which patiently wait for a connection request, accepts connection, then wait for some request string, and on getting the request string returns some response string, then again wait for next request and go on..Well you get the idea..

到目前为止

  1. 我已经与我的安卓和服务器建立了连接
  2. 发送和接收数据

这是我的客户端代码..

And this is my client code..

public class SocketMaster {
    private Socket clientSocket     =   null;
        BufferedReader socketReadStream =   null;
    public boolean connectToHost(String ip, int port){
        try {
            InetAddress serverAddr  =   InetAddress.getByName(ip);
            try {
                clientSocket        =   new Socket(serverAddr, port);
                socketReadStream    =   new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String line     =   null;
                String stringToSend =   "This is from client ...Are you there???";

                //Write to server..stringToSend is the request string..
                this.writeToServer(stringToSend);

                //Now read the response..
                while((line = socketReadStream.readLine()) != null){
                    Log.d("Message", line);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean writeToServer(String stringToSend){
        DataOutputStream dos        =   null;
        try {
            dos                         =   new DataOutputStream(clientSocket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        try {
            dos.write(stringToSend.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

我从另一个活动创建了一个 SocketMaster 对象,并调用 connectToHost 传递服务器的 ip 和端口..一切正常,我能够连接、发送和接收数据..

I create an object of SocketMaster from another activity and calls connectToHost passing ip and port of server..Everything works fine and I am able to connect, send and receive data..

现在我的问题是关于这些行

Now my question is regarding these lines

//Now read the response..
while((line = socketReadStream.readLine()) != null){
     Log.d("Message", line);
}

据我所知,执行此代码的线程

From what I understand, the thread that executes this code

  • 阻塞直到有数据要读取
  • 如果数据可用,读取它,然后因为循环再次阻塞,直到下一块数据到达

我不能在主线程上运行这段代码,因为它会阻塞我的 UI 活动......我可以考虑在后台线程中运行它,这是一种选择......

Simply I can't run this code on main thread as it will block my UI Activities..I can think of running this in a background thread, which is one option...

但理想情况下我想要的是...

But Ideally what I want is...

回调(我认为,Android 术语中的听众,熟悉 iOS 的任何人 CFSocketcallback),method ,当有数据可供读取时被调用,这样我就可以读取数据然后返回..

A callback (I think, listener in android terms, anyone familiar with iOS CFSocket and callback),method , which gets called when there is data available to read, so that I can just read data and then return..

android/java 中是否有这样的机制...如果没有(:-(),任何人都可以将我链接到一些在后台完成套接字处理的示例...

Is there any such mechanism in android/ java...If not ( :-( ), can anyone link me to some example where socket handling is done in background...

我不是在问自己创建回调机制..我只是问是否有任何侦听器在有数据要读取时通知您,当连接断开时..因此我可以消除上面给出的while循环......如果没有任何回调,我准备将此套接字移动到另一个线程,该线程循环并读取数据(事实上我已经完成了)...

I was not asking about creating a callback mechanism myself..I was just asking is there any listener present which notify you when there is data to read, when the connection got disconnected..Thus I can eliminate the above given while loop...If there isn't any callback, I am ready move this socket to another thread, which loops arounds and reads data (which infact I have already done)...

**

**

好吧,我是 2 个弱的老 android/java 开发人员,背后有 3.5 年的 c/c++/objective c 开发经验......所以我看到了低级别的 c 本机套接字(在使用时会阻止(可配置)读取)() 和 recv()) 和苹果的 CFSocket(它是 C 套接字本身,但提供了一个包装器来提供回调机制.如果没有现成的替代品,我愿意去做,但为什么要重新发明轮子?)...我开始将 java 理解为非常先进和高级的平台.我认为应该有一些更高级别的包装库潜伏在周围..所以我想通过开始赏金来增加这个线程的观众..

Well I am 2 weak old android/java developer with a good 3.5 years of c/c++/objective c development experience behind that... So I have seen low level c native sockets (which blocks(configurable) when use read() and recv()) and apple's CFSocket (which is C socket itself but provide a wrapper to provide callback mechanism).. I am not asking about coding a callback mechanism myself here (which I am whole heartedly ready to do if there is no readymade alternative present, but why reinvent the wheel again?)...I am beginning to understand java as very advanced and high level platform.. I thought there should be some higher level wrapper library lurking around..So I am thinking of increasing the audience to this thread by starting a bounty..

推荐答案

Java 中没有现成的回调.您可以使用 NIO 包中的类轻松实现一个.您主要需要 Selector 和 SocketChannel.如果您熟悉 select(2),应该很容易理解.如果没有,请尝试 NIO 教程.

There is no ready-made callback for this in Java. You can easily implement one using the classes in the NIO package. You mostly need Selector and SocketChannel. If you are familiar with select(2), should be easy to follow. If not, try a NIO tutorial.

http://download.oracle.com/javase/1.5.0/docs/api/java/nio/channels/SocketChannel.htmlhttp://download.oracle.com/javase/1.5.0/docs/api/java/nio/channels/Selector.html

http://download.oracle.com/javase/1.5.0/docs/api/java/nio/channels/SocketChannel.html http://download.oracle.com/javase/1.5.0/docs/api/java/nio/channels/Selector.html

在任何情况下,您都必须轮询套接字以检查是否有数据,而您不能在主线程上执行此操作.除非您的 android 应用程序应该在同一线程上管理多个连接,否则仅使用阻塞 IO 可能会容易得多.另一件要考虑的事情:如果这必须连续/长时间运行,您需要将其移至服务.即便如此,如果资源耗尽,操作系统也可以终止它,因此请准备好处理重新连接.

In any case, you will have to poll the socket to check if there is data, and you can't do this on the main thread. Unless your android app should manage multiple connections on the same thread, it might be a lot easier to just use blocking IO. Another thing to consider: if this has to run continuously/for a long time you need to move it to a service. Even then, the OS can kill it, if it runs out of resources, so be ready to handle reconnects.

HTH

这篇关于当有数据可以在socket中读取时,android中是否有任何回调机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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