首页 > 解决方案 > Java 代码无法在 android studio 中运行。端口通讯

问题描述

这段代码在 Eclipse 中运行良好,但是当我尝试在 android studio 中运行它时出现错误。我是学习java的新手,不知道如何调试它。创建新套接字时会发生错误,但在 eclipse 中可以正常工作。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Host IP.
    String hostName = "192.168.0.3";
    //Port Number.
    int portNumber = 6666;
    try (
        //Create a connection with IP on selected port.
        Socket echoSocket = new Socket(hostName, portNumber);
        //Create an outputStream with the connection.
        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
    ) {
        //Send data out the outputStream to server.
        out.println("Hello");
        //Exit so server knows to wait for the next connection.
        System.exit(1);
        //Catch Exceptions
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host " + hostName);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection to " +
        hostName);
        System.exit(1);
    }
}

02-09 17:48:09.920 13635-13635/? E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-09 17:48:09.970 13635-13635/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.geodesick.testapp, PID: 13635
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.geodesick.testapp/com.geodesick.testapp.MainActivity}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
        at android.app.ActivityThread.access$900(ActivityThread.java:175)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5603)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
        at java.net.InetAddress.getAllByName(InetAddress.java:214)
        at java.net.Socket.tryAllAddresses(Socket.java:109)
        at java.net.Socket.<init>(Socket.java:178)
        at java.net.Socket.<init>(Socket.java:150)
        at com.geodesick.testapp.MainActivity.onCreate(MainActivity.java:28)
        at android.app.Activity.performCreate(Activity.java:5458)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471) 
        at android.app.ActivityThread.access$900(ActivityThread.java:175) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:146) 
        at android.app.ActivityThread.main(ActivityThread.java:5603) 
        at java.lang.reflect.Method.invokeNative(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:515) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
        at dalvik.system.NativeStart.main(Native Method) 

标签: javaandroidsocketsnetworkonmainthread

解决方案


您不能在主 Android UI 线程上运行网络操作。

这是一个启动在它自己的线程上运行的Asynctask的解决方案:

class DoSocketOperation extends AsyncTask<String, Void, YourResult result> {
    protected YourResult doInBackground(String... urls) {
        // custom class to transport network result(you create it)
        YourResult result = nesw YourResult();
        //Host IP.
        String hostName = "192.168.0.3";
        //Port Number.
        int portNumber = 6666;
        try {
                //Create a connection with IP on selected port.
                Socket echoSocket = new Socket(hostName, portNumber);
                //Create an outputStream with the connection.
                PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);

                //Send data out the outputStream to server.
                out.println("Hello");
                result.setSucessOrSometing(true); (you create this)
                //Catch Exceptions
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                    hostName);
            System.exit(1);
        }
        return YourResult;
    }

    protected void onPostExecute(YourResult result) {

        if(result != null){
            // Now your on the main ui thread again, do something on the main ui thread with the result
        }
    }
}

推荐阅读