尝试连接到TCP Server时出现套接字异常

时间:2019-03-04 12:35:09

标签: java android sockets

我正在尝试使用以下简单方法检查是否可以建立与TCP服务器的连接:

public static boolean serverListening()
{
    Socket s = null;
    try
    {
        s = new Socket("192.168.42.213", 80);
        return true;
    }
    catch (Exception e)
    {
        Log.d("SocketException", "Exception",e);
        return false;
    }
    finally
    {
        if(s != null)
            try {s.close();}
            catch(Exception e){}
    }
}

我的服务器已经可以正常工作,因为我可以在模拟器内使用chrome连接到服务器,因此问题必须出在我的代码中。 如果我尝试运行代码,则会收到以下异常:

SocketException
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
    at java.net.Socket.connect(Socket.java:621)
    at java.net.Socket.connect(Socket.java:570)
    at java.net.Socket.<init>(Socket.java:450)
    at java.net.Socket.<init>(Socket.java:218)
    at com.example.batterymonitor.MainActivity.serverListening(MainActivity.java:104)
    at com.example.batterymonitor.MainActivity.onCreate(MainActivity.java:58)
    at android.app.Activity.performCreate(Activity.java:7136)
    at android.app.Activity.performCreate(Activity.java:7127)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

在android中,您无法在主线程上运行与网络相关的操作-您需要在其他线程上运行它们,例如:

Thread mThread = new Thread(new Runnable() {

@Override
public void run() {
    try  {
        //Put your code that you want to run in here(check your connection for example)
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
});

mThread.start