Android套接字错误或崩溃

时间:2016-02-08 17:14:05

标签: android sockets client

我正在使用以下代码将数据发送到tcp服务器,但是我遇到了错误。任何的想法? 我需要使用线程吗?我可以直接在函数上运行吗?

Msg& IPo& Proto是布局中的编辑框。 我认为我的问题是使用socket!

    Socket Clientsocketo;
String MsgOut="Nothing Happend";
TextView ad;

public void SendData(View v) throws IOException {
    EditText aa = (EditText)findViewById(R.id.EditText01);
    String Msg = aa.getText().toString();

    EditText ab = (EditText)findViewById(R.id.editText);
    String IPo = ab.getText().toString();

    EditText ac = (EditText)findViewById(R.id.editText2);
     int Porto  = Integer.parseInt(ac.getText().toString());

     InetAddress serverAddress = InetAddress.getByName(IPo);
    try{
        Clientsocketo = new Socket(serverAddress,Porto);
        ObjectOutputStream oos = new ObjectOutputStream(Clientsocketo.getOutputStream());
        oos.writeObject("Hello World");

        ObjectInputStream ois = new ObjectInputStream(Clientsocketo.getInputStream());
        String massagedf = (String)ois.readObject();
        ad.setText(massagedf);
        // mHandler.sendMessage(serverMessage);

        oos.close();
        ois.close();
    }
    catch(Exception e){
        ad.setText("Error");
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ad = (TextView) findViewById(R.id.textView);
}

1 个答案:

答案 0 :(得分:1)

必须在AsyncTask中处理网络操作。这允许网络操作继续而不阻塞主线程。使用AsyncTask的最佳方法是创建一个子类。像这样:

public class SendDataTask extends AsyncTask<Void, Void, Void> {

    Socket clientSocketTo;

    String msg;
    String ipo;
    int porto;
    InetAddress serverAddress;

    public SendDataTask(View v){
        EditText aa = (EditText) v.findViewById(R.id.EditText01);
        msg = aa.getText().toString

        EditText ab = (EditText) v.findViewById(R.id.editText);
        ipo = ab.getText().toString();

        EditText ac = (EditText) v.findViewById(R.id.editText2);
        porto = Integer.parseInt(ac.getText().toString());
        serverAddress = InetAddress.getByName(ipo);

    }

    protected void doInBackground(Void... arg){
        try{
            clientSocketTo = new Socket(ServerAddress,Porto);
            ObjectOutputStream oos = new ObjectOutputStream(clientSocketTo.getOutputStream());
            oos.weriteObject("Hello World")

            ObjectInputStream ois = new ObjectInputStream(clientSocketTo.getInputStream());
            String massagedf = (String) ois.readObject();
            ad.setText(massagedf);

            oos.close();
            ois.close();

        }catch (Exception e){

        }

    }

    protected void onPostExecute(Void result){

    }

}

要调用它,您将实例化传递视图的类,然后调用execute方法:

new SendDataTask(yourView).execute();

这些代码都没有经过测试......希望有所帮助!

更多信息: http://developer.android.com/reference/android/os/AsyncTask.html http://androidsrc.net/android-client-server-using-sockets-client-implementation/