1

我已经开始学习网络,并且一直在开发一个 android 应用程序来测试我所学到的东西。现在,我一直在关注网络上的教程,但似乎发生了一些奇怪的事情。当我包含互联网权限时,该程序有一个致命异常,但当我不包含它时,它会给我一个 EACCES denied 错误。

这是我的代码(请记住,我很多人只是在试验和尝试):

package com.test.sockettest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    public static final int TEST = 0;
    public static final int SERVER_PORT = 11235;

    TextView conversation;
    EditText messageInput;
    Button sendButton;
    ServerSocket servSock;
    List<Socket> outputs;
    Thread serverThread, clientThread;
    Handler conersationUpdater;
    String ipString;

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

        try {
            init();
        } catch (IOException e) {
            Log.d("SOCKET", "1" + e.toString());
            e.printStackTrace();
        }

    }

    private void init() throws IOException {
        findViewsById();
        serverThread = new Thread(new Server());
        askForIp();
        connect();
    }

    private void findViewsById() {
        conversation = (TextView) findViewById(R.id.conversation);
        messageInput = (EditText) findViewById(R.id.messageInput);
        sendButton = (Button) findViewById(R.id.sendButton);
    }

    class Server implements Runnable {

        @Override
        public void run() {
            Socket inputSock = null;
            try {
                servSock = new ServerSocket(SERVER_PORT);
            } catch (Exception e) {
                Log.d("SOCKET", "2" + e.toString());
            }
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    inputSock = servSock.accept();

                    Input in = new Input(inputSock);

                    new Thread(in).start();

                    outputs.add(new Socket(inputSock.getInetAddress(),
                            inputSock.getPort()));
                } catch (Exception e) {
                    Log.d("SOCKET", "3" + e.toString());
                }
            }
        }
    }

    class Input implements Runnable {
        private BufferedReader in;

        public Input(Socket socket) {
            try {
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
            } catch (Exception e) {
                Log.d("SOCKET", "4" + e.toString());
            }
        }

        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    String read = in.readLine();

                    conersationUpdater.post(new Update(read));
                } catch (Exception e) {
                    Log.d("SOCKET", "5" + e.toString());
                }

            }
        }
    }

    class Update implements Runnable {
        private String msg;

        public Update(String read) {
            msg = read;
        }

        public void run() {
            conversation
                    .setText(conversation.getText().toString() + msg + "\n");
        }
    }

    private void connect() throws IOException {
        InetAddress address = InetAddress.getByName(ipString);
        outputs.add(new Socket(address, SERVER_PORT));
    }

    private void askForIp() {
        final Dialog d = new Dialog(this);
        d.setContentView(R.layout.connect_dialog_layout);
        d.setTitle("Connect to IP...");

        final EditText ip = (EditText) findViewById(R.id.connectDialogIpBox);
        Button connect = (Button) findViewById(R.id.connectDialogButton);

        try {
            connect.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ipString = ip.getText().toString();
                    d.dismiss();
                }
            });
        } catch (Exception e) {
            Log.d("SOCKET", "11" + e.toString());
        }

        d.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

这是两个不同的清单文件:

1:

    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.test.sockettest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2:

    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.test.sockettest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

最后,两个错误日志:

1:

10-10 18:44:26.327: D/dalvikvm(32189): Late-enabling CheckJNI
10-10 18:44:26.517: D/SOCKET(32189): 11java.lang.NullPointerException
10-10 18:44:26.537: D/AndroidRuntime(32189): Shutting down VM
10-10 18:44:26.537: W/dalvikvm(32189): threadid=1: thread exiting with uncaught exception (group=0x41eec7c0)
10-10 18:44:26.537: E/AndroidRuntime(32189): FATAL EXCEPTION: main
10-10 18:44:26.537: E/AndroidRuntime(32189): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.sockettest/com.test.sockettest.MainActivity}: android.os.NetworkOnMainThreadException
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2330)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.app.ActivityThread.access$700(ActivityThread.java:154)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.os.Looper.loop(Looper.java:137)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.app.ActivityThread.main(ActivityThread.java:5368)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at java.lang.reflect.Method.invokeNative(Native Method)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at java.lang.reflect.Method.invoke(Method.java:525)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at dalvik.system.NativeStart.main(Native Method)
10-10 18:44:26.537: E/AndroidRuntime(32189): Caused by: android.os.NetworkOnMainThreadException
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1144)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at libcore.io.IoBridge.connect(IoBridge.java:112)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at java.net.Socket.startupSocket(Socket.java:566)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at java.net.Socket.<init>(Socket.java:225)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at com.test.sockettest.MainActivity.connect(MainActivity.java:134)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at com.test.sockettest.MainActivity.init(MainActivity.java:57)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at com.test.sockettest.MainActivity.onCreate(MainActivity.java:45)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.app.Activity.performCreate(Activity.java:5284)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
10-10 18:44:26.537: E/AndroidRuntime(32189):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2244)
10-10 18:44:26.537: E/AndroidRuntime(32189):    ... 11 more

2:

10-11 18:41:19.694: D/SOCKET(2086): 11java.lang.NullPointerException
10-11 18:41:19.704: D/SOCKET(2086): 1java.net.SocketException: socket failed: EACCES (Permission denied)
10-11 18:41:19.704: W/System.err(2086): java.net.SocketException: socket failed: EACCES (Permission denied)
10-11 18:41:19.714: W/System.err(2086):     at libcore.io.IoBridge.socket(IoBridge.java:576)
10-11 18:41:19.714: W/System.err(2086):     at java.net.PlainSocketImpl.create(PlainSocketImpl.java:201)
10-11 18:41:19.714: W/System.err(2086):     at java.net.Socket.startupSocket(Socket.java:559)
10-11 18:41:19.714: W/System.err(2086):     at java.net.Socket.<init>(Socket.java:225)
10-11 18:41:19.714: W/System.err(2086):     at com.test.sockettest.MainActivity.connect(MainActivity.java:132)
10-11 18:41:19.714: W/System.err(2086):     at com.test.sockettest.MainActivity.init(MainActivity.java:55)
10-11 18:41:19.714: W/System.err(2086):     at com.test.sockettest.MainActivity.onCreate(MainActivity.java:43)
10-11 18:41:19.714: W/System.err(2086):     at android.app.Activity.performCreate(Activity.java:5284)
10-11 18:41:19.714: W/System.err(2086):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
10-11 18:41:19.714: W/System.err(2086):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2244)
10-11 18:41:19.714: W/System.err(2086):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2330)
10-11 18:41:19.714: W/System.err(2086):     at android.app.ActivityThread.access$700(ActivityThread.java:154)
10-11 18:41:19.714: W/System.err(2086):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
10-11 18:41:19.714: W/System.err(2086):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 18:41:19.714: W/System.err(2086):     at android.os.Looper.loop(Looper.java:137)
10-11 18:41:19.714: W/System.err(2086):     at android.app.ActivityThread.main(ActivityThread.java:5368)
10-11 18:41:19.714: W/System.err(2086):     at java.lang.reflect.Method.invokeNative(Native Method)
10-11 18:41:19.714: W/System.err(2086):     at java.lang.reflect.Method.invoke(Method.java:525)
10-11 18:41:19.714: W/System.err(2086):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
10-11 18:41:19.714: W/System.err(2086):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
10-11 18:41:19.714: W/System.err(2086):     at dalvik.system.NativeStart.main(Native Method)
10-11 18:41:19.714: W/System.err(2086): Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
10-11 18:41:19.714: W/System.err(2086):     at libcore.io.Posix.socket(Native Method)
10-11 18:41:19.714: W/System.err(2086):     at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:181)
10-11 18:41:19.714: W/System.err(2086):     at libcore.io.IoBridge.socket(IoBridge.java:561)
10-11 18:41:19.714: W/System.err(2086):     ... 20 more

有什么想法吗?

4

1 回答 1

4
Caused by: android.os.NetworkOnMainThreadException

您正在尝试在主应用程序线程上执行网络 I/O。这不受支持,因为您将冻结 UI。请将您的网络 I/O 移动到后台线程,可能使用AsyncTask.

您将需要保留<uses-permission>元素,顺便说一句。

于 2013-10-11T22:53:56.383 回答