简体   繁体   English

使用Socket(Android)将顺序查询发送到服务器的最佳方法是什么?

[英]What is the best way to send sequential queries to the server using Socket (Android)?

I have two android devices, one acting as client and other acting as server. 我有两个Android设备,一个充当客户端,另一个充当服务器。 I am trying to get n number of images from the server device. 我正在尝试从服务器设备获取n个图像。 Previously, to fetch just one image I was using AsyncTask to create and open a Socket connection on the client device. 以前,仅获取一个图像,我使用AsyncTask在客户端设备上创建并打开Socket连接。 And a thread was running on the server device with ServerSocket . 使用ServerSocket在服务器设备上运行线程。 Both were configured to use the same port. 两者都配置为使用相同的端口。

I want to query some images. 我想查询一些图像。 Since the connection is on the same port, I don't think I can send those queries simultaneously? 由于连接在同一端口上,所以我认为我不能同时发送这些查询吗? Is that possible? 那可能吗?

I was thinking of creating a Queue of AsyncTask and execute them one by one. 我当时正在考虑创建一个AsyncTask Queue ,并一一执行它们。 But after reading some of the posts regarding this, it seems that AsyncTask is no the right way to do this and there's a limitation over number of AsyncTask threads. 但是在阅读了一些与此相关的文章后,似乎AsyncTask不是执行此操作的正确方法,并且AsyncTask线程数受到限制。

Android Developers website suggests that IntentService is useful to perform such tasks. Android开发者网站建议IntentService对于执行此类任务很有用。 So I wrote a basic class. 所以我写了一个基础课。

public class ClientSyncService extends IntentService {
    private JSONObject jsonData;
    private static final int SocketServerPORT = 4000;
    private String hostAddress;
    private Bitmap queryBitmap;
    private static final String TAG = "ClientSyncService";
    private String requestString;

    public ClientSyncService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        String jsonString = workIntent.getDataString();
        hostAddress = workIntent.getStringExtra("host-ipaddress");

        try {
            jsonData = new JSONObject(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            requestString = jsonData.getString("request");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        Socket socket = null;
        DataInputStream dataInputStream = null;
        DataOutputStream dataOutputStream = null;

        try {
            socket = new Socket(hostAddress, SocketServerPORT);
            dataOutputStream = new DataOutputStream(
                  socket.getOutputStream());
            dataInputStream = new DataInputStream(socket.getInputStream());
            dataOutputStream.writeUTF(jsonData.toString());
            Log.i(TAG, "waiting for response from host");

            if (requestString == null) {
                socket.close();
                return;
            }

            if (requestString == "query-display-picture" || requestString == "query-album-art") {
                Log.i(TAG, "waiting for image");
                byte buf[] = new byte[4096];
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int len;
                while((len = dataInputStream.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                    bos.flush();
                }
                if (bos.size() > 0) {
                    queryBitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
                } else {
                    Log.i(TAG, "bitmap is null");
                }
                Log.i(TAG, "bitmap created");

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close socket and streams
        }

    }

I'll figure the rest of the part out regarding broadcasting the data to the activity. 我将弄清楚剩下的部分,关于向活动广播数据。 I'm unclear about how to call this IntentService . 我不清楚如何调用此IntentService Do I prepare a queue and create new intent service for each image query or pass all the image requests to intent service and the service will have a loop and send request to the server and get data. 我是否准备队列并为每个图像查询创建新的意图服务,或者将所有图像请求传递给意图服务,该服务将循环并向服务器发送请求并获取数据。

TL;DR : I want to get n number of images/files from client (preferably using the same port). TL; DR :我想从客户端获取n个图像/文件(最好使用同一端口)。 What is the best way to do that? 最好的方法是什么? I have read about ThreadPoolExecutor and BlockingQueue but didn't try them out yet. 我已经阅读了有关ThreadPoolExecutorBlockingQueue但尚未尝试。 I am a bit new to threading. 我对线程有点陌生。

You can connect several sockets from a client to the same host:port, that will just create more sockets on the server, you'll need multiple threads accepting the connections on the server. 您可以将多个套接字从客户端连接到同一host:port,这只会在服务器上创建更多套接字,您将需要多个线程来接受服务器上的连接。

Or a single AsyncTask could be created with a list of images to fetch and get them all one after the other. 或者可以创建一个带有图像列表的AsyncTask来获取并逐个获取它们。 You could also make a single request for multiple images and get them all in the same socket (eg by sending size / data / size / data / ... or by using something as Google protocol buffers (a repeated field would be just fine). 您还可以对多个图像发出单个请求,然后将它们全部放在同一个套接字中(例如,通过发送大小/数据/大小/数据/ ...或使用某些内容作为Google协议缓冲区(重复的字段就可以了) 。

Last option could be to have a worker thread getting requests in a queue (one request per image) and processing them one by one. 最后一种选择是让工作线程在队列中获取请求(每个图像一个请求)并一个接一个地处理它们。

I think best way would be to get those images sequentially only. 我认为最好的方法是仅顺序获取这些图像。 But i think a normal java thread would be the best. 但是我认为普通的Java线程是最好的。

AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask. 理想情况下,应将AsyncTasks用于较短的操作(最多几秒钟)。如果需要使线程长时间运行,则强烈建议您使用java.util.concurrent pacakge提供的各种API,例如执行程序,ThreadPoolExecutor和FutureTask。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 发送android通知的最佳方式是什么 - What is the best way to send android notification 使用套接字连接android应用程序和php服务器的最佳方法是什么? - What is the best way to connect an android application and a php server using sockets? 在android中将大量事件发送到服务器的最佳方式 - Best way to send lots of events to server in android 在XMPP Android上发送笑脸的最佳方法是什么 - What is the best way to send smiley on xmpp android 通过套接字发送多个数据值的最佳方法是什么? - What is the best way to send multiple data values through a socket? 拥有推送通知服务器并在android设备和服务器之间发送数据的最佳方法是什么? - What is the best way to have a push notification server and send data between android device and server? 在用户之间发送图像并在Android中将其保存在服务器中一段时间​​的最佳方法是什么? - What's the best way to send images between users, and keep it in a server for a time in Android? Android-将JSON发送到远程服务器并等待异步响应的最佳方法是什么 - Android - What is the best way to send a JSON to a remote server and wait for an asynchronous response Android:与远程服务器通信的最佳方式是什么? - Android: what is the best way to commune with a remote server? 使用Java从Android向Web服务器发送和接收数据(POST和GET)的最佳方式? - Best way to send and receive data(POST and GET) from Android to web server using Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM