接收服务器响应时出错

时间:2017-01-09 14:22:33

标签: android python

我在PC和手机之间写了一个服务器 - 客户端通信。 PC是用Python编写的服务器,方便的是用Android(Java)编写的客户端。

注册后,双方都会发送他们的名字,一些JSON-String正在从手机发送到PC。 这没有任何例外

但是,当我在检查传入数据后尝试接收服务器应答时,出现以下异常:

I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@30ad25c
time:69321819
D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
W/System.err: java.net.SocketException: Socket is closed
W/System.err: at java.net.PlainSocketImpl.checkNotClosed(PlainSocketImpl.java:116)
W/System.err: at java.net.PlainSocketImpl.getInputStream(PlainSocketImpl.java:213)
W/System.err: at java.net.Socket.getInputStream(Socket.java:363)
W/System.err: at com.dmd_data.soft_zeiterfassung.daten_transfer$MyClientTask.doInBackground(daten_transfer.java:267)
W/System.err:     at com.dmd_data.soft_zeiterfassung.daten_transfer$MyClientTask.doInBackground(daten_transfer.java:108)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
I/Timeline: Timeline: Activity_launch_request id:com.dmd_data.soft_zeiterfassung time:69322601
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@30ad25c time:69323717

我的Android代码如下所示:

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

    String dstAddress;
    int dstPort;
    String message = "";
    String response = "";
    String failMessage = "";
    int timeoutMs;
    String kontoVorname;
    String kontoNachname;
    String userName;

    MyClientTask(String addr){

        dstAddress = addr;
        dstPort = 9090;
        timeoutMs = 1000;
        SharedPreferences systemDATA = getSharedPreferences("konto",0);
        kontoVorname = systemDATA.getString("editText_vorname", "");
        kontoNachname = systemDATA.getString("editText_nachname", "");
        userName = kontoVorname+" "+kontoNachname;
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        JSONArray arb_List = new JSONArray();
        JSONArray mat_List = new JSONArray();

        Cursor arb_Cursor = My_Database.getAllData();

        if (arb_Cursor.getCount() == 0){

            Intent click_datenbank = new Intent(daten_transfer.this,pop_datenbank.class);
            startActivity(click_datenbank);

        }else {

            Socket socket = null;

            try {

                SocketAddress sock_addresse = new InetSocketAddress(dstAddress, dstPort);
                socket = new Socket();
                socket.connect(sock_addresse, timeoutMs);

            } catch (UnknownHostException e) {
                e.printStackTrace();
                failMessage = "IP-ADRESSE UNBEKANNT:\n" + e.toString();

            } catch (IOException e) {
                e.printStackTrace();
                failMessage = "PC NICHT ERREICHBAR:\n"+ e.toString();
            }

            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
            String dateTime = sdf.format(new Date());

            //Receive server name
            ByteArrayOutputStream bAPS_Name = new ByteArrayOutputStream(25000);
            byte[] bytes_Name = new byte[25000];
            int int_server;
            InputStream input_Name = null;
            try {
                input_Name = socket.getInputStream();
                int_server = input_Name.read(bytes_Name);
                bAPS_Name.write(bytes_Name, 0, int_server);
                response += bAPS_Name.toString("UTF-8");

            } catch (IOException e) {
                e.printStackTrace();
            }

            //Create datalist
            arb_Cursor.moveToFirst();
            while (arb_Cursor.isAfterLast() == false) {

                int totalArbeit = arb_Cursor.getColumnCount();
                JSONObject row_SEND = new JSONObject();

                for( int i=0 ;  i< totalArbeit ; i++ ){

                    if( arb_Cursor.getColumnName(i) != null ){

                        try{
                            if( arb_Cursor.getString(i) != null ){

                                row_SEND.put(arb_Cursor.getColumnName(i) ,  arb_Cursor.getString(i) );
                            }
                            else
                            {
                                row_SEND.put( "NONE" , "---" );
                            }
                        }
                        catch( Exception e )
                        {
                            e.getMessage();
                            failMessage = "SORRY,SOMETHING GOES WRONG:\n" + e.toString();
                        }
                    }
                }
                arb_List.put(row_SEND);
                arb_Cursor.moveToNext();
            }
            arb_Cursor.close();

            //Send
            JSONObject json = new JSONObject();

            try (OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)){

                json.put("User",userName);
                json.put("Datetime",dateTime);
                json.put("Datalist",arb_List);
                writer.write(json.toString());

            } catch (Exception e) {
                e.printStackTrace();
                failMessage = "SORRY, SOMETHING GOES WRONG...:\n" + e.toString();
            }

            // Until here it works
            //##################################################################################

            InputStream input_Response = null;
            try {
                input_Response = socket.getInputStream();
                BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(input_Response));
                String line = "";
                while((line = bufferedReader.readLine()) != null) {
                    message += line;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            //##################################################################################
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        if (failMessage.length()!= 0){
            Toast.makeText(daten_transfer.this,failMessage,Toast.LENGTH_LONG).show();
            //Intent click_transfer = new Intent(daten_transfer.this,pop_wlan.class);
            //startActivity(click_transfer);
        }
        else{
            SharedPreferences systemDATA = getSharedPreferences("konto",0);
            SharedPreferences.Editor editor = systemDATA.edit();
            //editor.putString("failmessage",failMessage);
            //editor.commit();
            editor.putString("response",response);
            editor.commit();

            if (response.length() != 0){
                Intent click_transfer = new Intent(daten_transfer.this,pop_tansfer.class);
                startActivity(click_transfer);
            }

            textView_show.setText(message);
        }
    }
}

我尽我所能尝试了一切,但不管我做什么,我总能得到答案:

java.net.SocketException: Socket is closed

1 个答案:

答案 0 :(得分:0)

完成out流式传输后,关闭OutputStreamWriter writer变量。套接字正忙,因为您仍在使用它。 请尝试以下代码段

json.put("User",userName);
json.put("Datetime",dateTime);
json.put("Datalist",arb_List);
writer.write(json.toString());
writer.close();

使用后关闭套接字也是一种很好的做法。