客户端 - 服务器安卓聊天应用程序 - NetworkOnMainThreadException

时间:2017-01-10 11:49:46

标签: java android sockets networking

我正在为Android轻松聊天。 我正在使用this tutorial这样做。我有简单的android客户端和java客户端。

我从几个步骤开始:

  1. 启动服务器||消息服务器:“等待客户端连接”
  2. 启动客户端||服务器中没有消息
  3. 点击按钮||消息服务器:“客户端已连接”和“来自客户端的消息:                连接“和”服务器已经结束。“
  4. Android客户端因NetworkOnMainThreadException而崩溃
  5. 步骤3的消息将出现在创建客户端上,因此当我启动应用程序时。当我点击按钮时,它应该向服务器发送消息。它崩溃了这个错误:

    01-10 10:31:26.892 27458-27458/com.example.rachel.testapp E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.example.rachel.testapp, PID: 27458
     java.lang.IllegalStateException: Could not execute method for android:onClick
         at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
         at android.view.View.performClick(View.java:5637)
         at android.view.View$PerformClick.run(View.java:22429)
         at android.os.Handler.handleCallback(Handler.java:751)
         at android.os.Handler.dispatchMessage(Handler.java:95)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6119)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
      Caused by: java.lang.reflect.InvocationTargetException
         at java.lang.reflect.Method.invoke(Native Method)
         at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
         at android.view.View.performClick(View.java:5637) 
         at android.view.View$PerformClick.run(View.java:22429) 
         at android.os.Handler.handleCallback(Handler.java:751) 
         at android.os.Handler.dispatchMessage(Handler.java:95) 
         at android.os.Looper.loop(Looper.java:154) 
         at android.app.ActivityThread.main(ActivityThread.java:6119) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
      Caused by: android.os.NetworkOnMainThreadException
         at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
         at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
         at java.net.SocketOutputStream.write(SocketOutputStream.java:157)
         at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
         at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
         at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295)
         at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
         at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
         at java.io.BufferedWriter.flush(BufferedWriter.java:254)
         at com.example.rachel.testapp.MainActivity.sendMessage(MainActivity.java:88)
         at java.lang.reflect.Method.invoke(Native Method) 
         at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
         at android.view.View.performClick(View.java:5637) 
         at android.view.View$PerformClick.run(View.java:22429) 
         at android.os.Handler.handleCallback(Handler.java:751) 
         at android.os.Handler.dispatchMessage(Handler.java:95) 
         at android.os.Looper.loop(Looper.java:154) 
         at android.app.ActivityThread.main(ActivityThread.java:6119) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
    

    我有像这样的Android应用程序

    public class MainActivity extends AppCompatActivity
    {
        private static final String hostname = "localhost";
        private static final int portnumber = 60125;
        private static final String debugString = "debug";
        private Socket socket = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            new Thread()
            {
                @Override
                public void run()
                {
                    try
                    {
                        Log.i(debugString, "Attempting to connect to server");
                        socket = new Socket(hostname, portnumber);
                        Log.i(debugString, "Connection established");
    
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        bw.write("Connected");
                        bw.newLine();
                        bw.flush();
    
                        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        System.out.println("Message from server:" + br.readLine());
    
    
                    } catch (IOException e)
    
                    {
                        Log.e(debugString, e.getMessage());
                        //e.printStackTrace();
                    }
                }
            }.start();
    
    
    
        }
    
        public void sendMessage(View view)
        {
            Toast.makeText(getApplicationContext(), "Klik", Toast.LENGTH_LONG).show();
    
            EditText editText = (EditText) findViewById(R.id.editText);
            BufferedWriter bw =null;
    
            try
            {
                bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    
                bw.write(editText.getText().toString());
                bw.newLine();
                bw.flush();
            }
            catch (IOException e)
            {
                Log.e(debugString, e.getMessage());
            }
    
    
    
    
        }
    
    }
    

    和java服务器

    public class main 
    {
    
        private static final int portnumber = 60125;
    
        public static void main(String[] args) 
        {
            ServerSocket serverSocket = null;
            try
            {
                System.out.println("Serwer port: "+ portnumber);
                serverSocket = new ServerSocket(portnumber);
    
                System.out.println("Waiting to connect");
                Socket socket = serverSocket.accept();
                System.out.println("Client connected");
    
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                bw.write("Message from server");
                bw.newLine();
                bw.flush();
    
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String data;
                while((data = br.readLine()) != null)
                System.out.println("Message from client:"+data);
    
    
                System.out.println("Server has ended.");
            }
            catch(IOException e)
            {
                e.printStackTrace();            
            }
    
        }
    
    
    
    
    }
    

1 个答案:

答案 0 :(得分:0)

您无法在主线程上进行网络操作。在后台任务中执行此操作。更好地使用AsyncTask或更改为

 new Thread(new Runnable() {
            @Override
            public void run() {
                try
                {
                    Log.i(debugString, "Attempting to connect to server");
                    socket = new Socket(hostname, portnumber);
                    Log.i(debugString, "Connection established");

                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    bw.write("Connected");
                    bw.newLine();
                    bw.flush();

                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    System.out.println("Message from server:" + br.readLine());


                } catch (IOException e)

                {
                    Log.e(debugString, e.getMessage());
                    //e.printStackTrace();
                }
            }
        }).start();