错误是什么?Android编程新手



我正在尝试在Android中实现一个发送消息的服务器客户端程序。你能告诉我我的代码中有什么错误以及如何纠正吗?服务器运行正常,但客户端程序有一个错误。

这是服务器代码,运行良好。

package com.app.MyServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class MyServer extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView tv = (TextView) findViewById(R.id.TextView01);
    tv.setText("Nothing from client yet");
    this.myCommsThread = new Thread(new CommsThread());
    this.myCommsThread.start();
}
@Override
protected void onStop() {
    super.onStop();
    try {
            // make sure you close the socket upon exiting
            ss.close();
    } catch (IOException e) {
            e.printStackTrace();
    }
}
Handler myUpdateHandler = new Handler() {
    public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_ID:
                    TextView tv = (TextView) findViewById(R.id.TextView01);
                    tv.setText(mClientMsg);
                    break;
            default:
                    break;
            }
            super.handleMessage(msg);
    }
};
class CommsThread implements Runnable {
    public void run() {
            Socket s = null;
            try {
                    ss = new ServerSocket(SERVERPORT );
                    Log.v("SErver ",ss.toString());
            } catch (IOException e) {
                    e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {
                    Message m = new Message();
                    Log.v("Message ",m.toString());
                    m.what = MSG_ID;
                    try {
                            if (s == null && ss!=null)
                            {
                                s = ss.accept();
                                Log.v("Drrr","It is not null");
                            }
                            else
                                Log.v("The thing is ", "ss is null");
                            BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                            String st = null;
                            st = input.readLine();
                            mClientMsg = st;
                            myUpdateHandler.sendMessage(m);
                    } catch (IOException e) {
                            Log.v("Error ",e.toString());
                            e.printStackTrace();
                    }
            }
    }
}
}

客户代码:

package com.exercise.AndroidClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 textOut = (EditText)findViewById(R.id.textout);
 Button buttonSend = (Button)findViewById(R.id.send);
 textIn = (TextView)findViewById(R.id.textin);
 buttonSend.setOnClickListener(buttonSendOnClickListener);
}
 protected class connect extends AsyncTask<String,DataInputStream,String>
 {

@Override
protected void onPreExecute() 
{
        Log.i( "makemachine", "onPreExecute()" );
     // TODO Auto-generated method stub
     Socket socket = null;
     DataOutputStream dataOutputStream = null;
     DataInputStream dataInputStream = null;
     try {
      socket = new Socket("10.0.2.2", 5000);
      dataOutputStream = new DataOutputStream(socket.getOutputStream());
      dataInputStream = new DataInputStream(socket.getInputStream());
      dataOutputStream.writeUTF(textOut.getText().toString());
      publishProgress(dataInputStream);
     }
     catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     finally
     {
      if (socket != null)
      {
       try {
        socket.close();
       }
       catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
      if (dataOutputStream != null){
       try {
        dataOutputStream.close();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
      if (dataInputStream != null){
       try {
        dataInputStream.close();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
     }
        super.onPreExecute();
}
protected void onProgressUpdate(DataInputStream... dataInputStream) {
    Log.v("The mesage length is ",dataInputStream.toString());
    textIn.setText(dataInputStream.toString());
}

@Override
protected void onPostExecute( String result ) 
{
        super.onPostExecute(result);
        Log.i( "connected", "onPostExecute(): " + result );
}
@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    return null;
}
 }
 Button.OnClickListener buttonSendOnClickListener
  = new Button.OnClickListener(){

 public void onClick(View arg0) 
 {
     Log.v("Sending the message ","to the server");
  }};
}

日志为:

 02-06 01:55:31.421: E/AndroidRuntime(582): FATAL EXCEPTION: main
 02-06 01:55:31.421: E/AndroidRuntime(582): android.os.NetworkOnMainThreadException
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at libcore.io.IoBridge.connect(IoBridge.java:112)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.Socket.startupSocket(Socket.java:566)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.Socket.tryAllAddresses(Socket.java:127)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.Socket.<init>(Socket.java:177)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.Socket.<init>(Socket.java:149)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at com.exercise.AndroidClient.AndroidClient$1.onClick(AndroidClient.java:45)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.view.View.performClick(View.java:3511)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.view.View$PerformClick.run(View.java:14105)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.os.Handler.handleCallback(Handler.java:605)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.os.Handler.dispatchMessage(Handler.java:92)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.os.Looper.loop(Looper.java:137)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.app.ActivityThread.main(ActivityThread.java:4424)
02-06 01:55:31.421: E/AndroidRuntime(582):  at java.lang.reflect.Method.invokeNative(Native Method)
02-06 01:55:31.421: E/AndroidRuntime(582):  at java.lang.reflect.Method.invoke(Method.java:511)
02-06 01:55:31.421: E/AndroidRuntime(582):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-06 01:55:31.421: E/AndroidRuntime(582):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-06 01:55:31.421: E/AndroidRuntime(582):  at dalvik.system.NativeStart.main(Native Method)

我读到我们无法在UI线程中实现网络线程。这就是我使用AsyncTask线程的原因。但即便如此,我还是遇到了NetworkOnMainThread异常。请告诉我程序中的错误以及如何纠正它们。

That is why I am using the AsyncTask thread.But even then I get the NetworkOnMainThread Exception.

事实上你不是。您需要调用execute(),而不是直接调用doInBackground(),否则您不会使用AsyncTask提供的任何管道,而只是直接在UI线程中调用该方法。

您正在执行的操作textIn.setText(dataInputStream.readUTF());

在doInBackground()方法中。而doInBackground应该只包含不属于事件线程的操作,因此,使用

publishProgress(param);实现这一点。

相关内容

最新更新