使用套接字时Android崩溃

时间:2018-12-27 15:24:39

标签: java android

我正在尝试从Windows服务器上的C ++ TCP套接字获取数据包。我用Putty测试了我的服务器。它正在工作,但是我无法从Android创建客户端。我测试了这段代码,当我打开应用程序时,它立即崩溃了。

API级别:26 测试电话:Oreo 8.0

编辑:现在连接后崩溃3-4秒。我尝试了其他TCP客户端应用程序,这些程序可以正常工作。

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

  Intent intent = getIntent();
  String message = intent.getStringExtra(LoginActivity.EXTRA_MESSAGE);

  // Capture the layout's TextView and set the string as its text
  TextView textView2 = findViewById(R.id.textView2);
  TextView textView = findViewById(R.id.textView);
  textView2.setText(message);
  ip = message;

  Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        TextView textView = findViewById(R.id.textView);
        Socket socket = new Socket("192.168.1.108", 2970);
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
        textView.setText(in.readLine());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  });
  thread.start();
}

2 个答案:

答案 0 :(得分:1)

我认为这应该是您的错误:android.os.NetworkOnMainThreadException

尝试创建线程并在其周围包装套接字调用

        Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            //Do your socket call here

        }
    });

    thread.start();

也不要忘记在线程外(文本视图)进行ui更新

答案 1 :(得分:1)

根据mangusta的建议,您可以尝试在除mainThread之外的其他线程上进行连接。

我在这里添加一个可能的解决方法:

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

    Intent intent = getIntent();
    String message = intent.getStringExtra(LoginActivity.EXTRA_MESSAGE);

    // Capture the layout's TextView and set the string as its text
    TextView textView2 = findViewById(R.id.textView2);
    TextView textView = findViewById(R.id.textView);
    textView2.setText(message);
    ip = message;
    new Thread(new Runnable() {
        public void run() {
            // a potentially time consuming task
            try {
                Socket socket = new Socket("192.168.1.108", 2970);
                final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                textView.post(new Runnable() {
                    public void run() {
                        textView.setText(in.readLine());
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();

                textView.post(new Runnable() {
                    public void run() {
                        textView.setText(e.toString());
                    }
                });
            }

        }
    }).start();
}

这只是尝试连接的一种快速实现。