简体   繁体   中英

AsyncTask to create a Socket

I have some problems setting up a Socket connection.

From what I found, the constructor Socket(InetAddress dstAddress, int dstPort) cannot be use in the main thread.

This is what I tried :

In CreateSocketTask.java

public class CreateSocketTask extends AsyncTask<InetAddress,Void,Socket>{
<...>

@Override
protected Socket doInBackground(InetAddress... params) {
    try
    {
        socket = new Socket(params[0], port);
        return socket;

    } catch(ConnectException e) {
        Log.e("SocketClient", "Error", e);

        return null;



    } catch(IOException e) {
        Log.e("SocketClient", "Error", e);
        return null;
    }
}

protected void onPostExecute() {
    }
}

And then in my SocketClient.java :

public class SocketClient implements Runnable{
<...>
public void run()
{
    try
    {
        InetAddress serverAddress = InetAddress.getByName(serverIp);

        new CreateSocketTask().execute(serverAddress);


        try {
        /*Here, I want to retrieve the result of my CreateSocketTask to use it in my new Thread, I tried CreateSocketTask.get() but without any success*/

        new Thread(new SocketReader(new BufferedReader(new InputStreamReader(socket.getInputStream())), observerList)).start();
        }

How do I set up a socket connection?


Would this work ?

Instead of creating a service, may I simply create a new Thread to perform my Socket creation ? Like that :

Thread SocketThread =new Thread(new Runnable() {

    @Override
    public void run() {
        try {Socket socket = new Socket(serverAddress,port);}
        catch (IOException e){}
        }
    });
    SocketThread.run();
    try {
    new Thread(new SocketReader(new BufferedReader(new InputStreamReader(socket.getInputStream())), observerList)).start();
    }

Don´t use an AsyncTask , the purpose for this class is to do little work according to the documentation "used for short operations (a few seconds at the most.)"

So you better implement a Service to do your I/O requests http://developer.android.com/guide/components/services.html

AsyncTask is not useful when you want to use sockets. You should use AsyncTask when you need to do a intensive work in a separeted thread and then at the end change the UI state. The classic application is making an HTTP request to retrieve some data from remote server and then update for example an Adapter and then UI component.

You should remember that service can be used to do background work anyway if you run the service does not mean you make the work in a separate thread. The documentation says

service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

So you have to start a separate thread where you handle the server side and accepts connection. Each connection should be handled in a separate thread so you can have multiple connection at the same time.

The same concepts are valid for client side.

If you want to update the UI you can use a callback methods and update the UI in the main thread.

Problem solved.

In public class SocketClient implements Runnable I have the method public SocketClient(int port, String serverIp, Collection<Observer> observerList, Context context) in which I happen to create socket = new Socket(serverAddress, port) .

To make this work in my MapEngine.java , I simply added

this.SocketClient = new SocketClient(-THEPORT-,-THEIPADDRESS-,null,this)

in my constructor and then I created my socket by calling

new Thread(SocketClient).start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM