【问题标题】:ServerSocket.accept() terminates the Android ApplicationServerSocket.accept() 终止 Android 应用程序
【发布时间】:2014-02-01 23:26:11
【问题描述】:

伙计们。我是 Android 和论坛的新手。我有以下关于套接字通信的问题。

package com.example.d5server2;

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

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textview1;
    Button button1;
    ServerSocket serversocket1 = null;
    Socket socket1 = null;
    int i=16;

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

        textview1 = (TextView) findViewById(R.id.textView1);
        button1 = (Button) findViewById(R.id.button1);

    }

    @Override
    protected void onResume(){
        super.onResume();

        try {
            serversocket1 = new ServerSocket(9999);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            socket1 = serversocket1.accept();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

当我在手机上运行此代码时,应用程序会终止。但是,如果我删除该行

socket1 = serversocket1.accept();

它没有这样做。我检查了许多示例代码,其中大多数使用了类似的编码。我找不到我的应用程序被终止的任何原因。我在网上搜索但无法得到任何答案。感谢您的所有帮助。

【问题讨论】:

  • 您的日志中有哪些错误?
  • 是否抛出异常?
  • 我没有得到任何异常我只知道我的应用程序在启动时被终止
  • 清单中可能没有特权? <uses-permission android:name="android.permission.INTERNET" />
  • 我添加了权限。我想我错过了一个简单的点,因为我是初学者。你认为有什么简单的错误会导致这种情况吗?

标签: java android sockets communication serversocket


【解决方案1】:

猜测,因为您没有提供足够的信息,例如堆栈跟踪,'serverSocket' 可能为 null,因为您不正确的异常处理允许应用程序继续,即使 ServerSocket 的初始化抛出异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多