套接字AsyncTask不会在代码

时间:2015-07-02 20:12:13

标签: java android sockets

我有以下代码,以便在android中执行异步任务以连接到套接字。

调用asynctask是

new SocketAsyncTask().execute("abc");

import android.os.AsyncTask; import android.util.Log;

import java.io.IOException; import java.net.Socket;

public class SocketAsyncTask扩展了AsyncTask {

private static String connectionURL ="MY_URL" ;
private static int port = 3000;

@Override
protected Void doInBackground(String... uri) {
     try {
         String sentence;
         String modifiedSentence;
         Socket clientSocket = new Socket(connectionURL, port);
         Log.d("In socket",clientSocket.isConnected() + "");

         if (clientSocket.isConnected()) {
             Log.d("Client connection Successfull!!", "true");
             //System.out.print("Connection Successfull!!");
         } else {
             //System.out.print("Connection Not Successfull!!");
             Log.d("Client connection not Successfull!!", "true");
         }
        /*DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');
        modifiedSentence = inFromServer.readLine();
        System.out.println("FROM SERVER: " + modifiedSentence);*/
         clientSocket.close();
     }catch (IOException exp) {

     }
 return null;
}

}

输出会打印“In socket”字符串,但是,它不会记录“Client connection successfull”或“Client connection not successfull”。我试过调试它,但它基本上做了一些奇怪的事情。它在logcat中打印“In socket”但似乎没有在该断点处停止。

1 个答案:

答案 0 :(得分:1)

首先记录isConnected()没有意义。如果构造函数没有抛出异常,则套接字 连接。 isConnected()测试在您进行测试时不可能是错误的。

这里的问题是你忽略了你应该记录的异常。