Android TCP client

前端 未结 1 1781
悲&欢浪女
悲&欢浪女 2020-12-18 11:53

I\'m currently working on a tcp client in Android. I want to connect my android device to a tcp server on my computer and receive the data once every 2 seconds. The problem

相关标签:
1条回答
  • 2020-12-18 12:35

    You need to paste the exception that you are getting to cause the force close, before anyone can provide decent help.

    But some suggestions that might solve the problem.

    • Most likely to be the problem, viewText.setText can only be called from the UI thread. There's quite a few ways to handle this. You can use AsyncTask or if you have an Activity reference you can use runOnUIThread and pass in a runnable that calls setText.
    • Move checkin = sk.getInputStream(); to before the loop. There's no reason to get the strem every cycle through the loop.
    • Do not create the BufferedReader every cycle through the loop. Move it before the loop
    • .sleep(2000) does not guarantee exactly 2 seconds.

    I'm having some code formatting issues so I apologize.

     private class DownloadFilesTask extends AsyncTask<Void, String, Void> {
         protected Long doInBackground(Void... nothing) {
             try {                    
                sk=new Socket(server,port);
            publishProgress("connected");       
                flag = true;
        } catch (UnknownHostException e) {      
            publishProgress("failed 1 socket");
            flag = false;
        } catch (IOException e) {                   
            publishProgress("failed 2 socket");
            flag = false;
        }
    
        while (flag == true){               
            try {
                checkin = sk.getInputStream();
                checkint = checkin.available();
    
                if (checkint > 0){
                    try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                        received = in.readLine();
                        publishProgress(received);
    
                    } catch (IOException e) {
                        publishProgress("failed to receive");
                    }
                }
    
            Thread.sleep(2000);
            } catch (IOException e) {
                updateProgress(
    
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        return;
     }
    
     protected void onProgressUpdate(String... progress) {
        viewsurface.setText(progress[0]);
     }
    
     protected void onPostExecute(Void result) {
         //nothing
     }
    
     }
    
    0 讨论(0)
提交回复
热议问题