代码Socket clientSocket = new Socket();在Android应用程序崩溃。为什么?

时间:2015-05-01 17:56:06

标签: java android sockets

我正在使用标准客户端代码将字符串发送到我的服务器。当我从eclipse运行java项目时,它工作得很完美,但是当我通过Android应用程序上的按钮运行相同的代码时它不起作用。调试后,我在行

中尝试了代码崩溃

Socket clientSocket = new Socket(“192.168.1.91”,6789);

请帮帮我。

    public void button2OnClick(View k){

    //Testing Server Connection
    try{

        String sentence;

        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
        Socket clientSocket = new Socket("192.168.1.91", 6789);
        Button button=(Button) k;
        ((Button) k).setText("Done");
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = "connection with android successful";
        outToServer.writeBytes(sentence + '\n');
        modifiedSentence = inFromServer.readLine();
        clientSocket.close();


    }
    catch(Exception IO){

    }



}

1 个答案:

答案 0 :(得分:3)

因为您是从主线程执行的,所以您已将其移动到线程。

new Thread(new Runnable(){
    public void run(){
        //open socket
    }
}).start();

接下来,您必须在AndroidManifest上添加互联网权限

<uses-permission android:name="android.permission.INTERNET" />

在android中我们可以使用AsyncTask,当后台操作完成时,可以在主线程上执行操作。它将是:

new AsyncTask<Void,Void,Void>(){

        @Override
        protected Void doInBackground(Void... params) {
            String modifiedSentence;
            BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
            Socket clientSocket = new Socket("192.168.1.91", 6789);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            sentence = "connection with android successful";
            outToServer.writeBytes(sentence + '\n');
            modifiedSentence = inFromServer.readLine();
            clientSocket.close();

            return null;
        }

        @Override
        protected void onPostExecute() {
            super.onPostExecute();
            Button button=(Button) k;
            ((Button) k).setText("Done");
        }
    }.execute();