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

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

问题描述

好吧,我熟悉C语言socket编程,iOS的environment..But现在正试图连接我的Andr​​oid和我通过套接字的远程服务器...作为一个启动,我写了一个在C简单的服务器程序并运行它我的桌面而耐心地等待一个连接请求,接​​受连接,然后等待一些请求字符串,并在得到请求字符串返回一些响应字符串,然后再等待下一个请求,去on..Well你的想法..

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. 我已经与我的Andr​​oid和服务器
  2. 的连接
  3. 在发送和接收的数据

这是我的客户code ..

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和server..Everything端口工作正常,我能够连接,发送和接收数据。

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

据我了解,执行该code线

From what I understand, the thread that executes this code

  • 阻塞,直到有数据读取
  • 如果可用数据,读取环路的话,因为它,再次阻塞,直到 数据的下一块到达
  • blocks until there is data to read
  • if data available, read it, then because of loop again blocks until next chunk of data arrives

只要我不能运行在主线程此code,因为它会阻止我的UI Activities..I能想到在后台线程,这是一个选项...

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...

A 回调(我认为,听者在机器人方面,任何人都熟悉的iOS <一个href="http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFSocketRef/Reference/reference.html">CFSocket和<一href="http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFSocketRef/Reference/reference.html">callback),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...

编辑: 我不是问有关创建回调机制myself..I刚才问的是有没有监听器present它通知你当有数据读取,在连接了disconnected..Thus我可以消除上述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岁疲软的Andr​​oid / Java开发人员具有良好的3.5年C / C ++ / Objective C的开发背后的经验...所以,我已经看到了低级别的C本机插槽(其中块(配置)在使用时读()和recv())和苹果的CFSocket(这是C插座本身,而是提供了一个包装,以提供回调机制).. 我不是问这里的编码回调机制本人(我是全全心全意做准备,如果没有现成的替代present,但为什么又重新发明轮子呢?)......我开始明白Java作为非常先进的,高层次的平台。我认为应该有一些更高层次的包装库潜伏around..So我想通过启动赏金增加了观众对这一主题的。

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包。你大多需要选择和的SocketChannel。如果您熟悉选择(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.

<一个href="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/SocketChannel.html http://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.

心连心

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

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