我是android新手,但不是sockets。我有一个带有运行 UAVServer 线程的按钮的 GUI。当我点击它时,服务器应该监听客户端。代码行...
Socket client = serverSocket.accept();
...应该阻止,直到客户端连接。但它只是崩溃说“不幸的是,DroidUAV 已经停止。”
public class UAVServer extends Thread {
private String TAG = UAVServer.class.getSimpleName();
@Override
public void run() {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(12345);
Log.d(TAG, "Fails at the next line of code");
Socket client = serverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这看起来很简单,为什么会崩溃?还有android如何处理阻塞端口,这可能与它有关。如果它在 wifi 上,我认为这将取决于路由器来解锁端口。但是,如果我只是在使用 4G 呢?
注意:使用权限 android:name="android.permission.INTERNET" 在我的清单文件中。
编辑:我一定是做错了什么,因为我只是试图让它运行客户端而不是它在这条线上崩溃......
Socket s = new Socket("192.168.1.102",4444);
编辑:添加错误...
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3071)
at android.view.View.performClick(View.java:3538)
at android.widget.CompoundButton.performClick(CompoundButton.java:103)
at android.view.View$PerformClick.run(View.java:14319)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:5099)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:991)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3066)
... 12 more
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1190)
at libcore.io.BlockGuardOs.accept(BlockGuardOs.java:54)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:98)
at java.net.ServerSocket.implAccept(ServerSocket.java:202)
at java.net.ServerSocket.accept(ServerSocket.java:127)
at com.example.droiduav.UAVServer.run(UAVServer.java:19)
at com.example.droiduav.MainActivity.onToggleServer(MainActivity.java:31)
... 15 more