Android需要帮助!如何让Tcp Client从服务器接收数据?

时间:2015-06-15 13:56:51

标签: java android sockets tcp

我想创建一个可以为服务器发送和接收数据的TCP客户端。我使用Hercules(TCP / UDP测试程序)作为服务器。我的代码可以发送字符串"提交"到服务器。我尝试让我的代码可以从Hercules接收数据,但它不起作用。我必须做什么来编辑它?

这是我的MainActivity代码

public class MainActivity extends Activity {

// Used to reference UI elements of main.xml
private TextView text,serverResponse;
private EditText ipBox;
private EditText portBox;
private ToggleButton connect;
private Button send;
private static final String TAG = "CClient"; 
private String ipAddress;
private Socket client;
private DataOutputStream outToServer;
private DataInputStream inFromServer;
private boolean connected = false;   
private final int START = 0xffffff;
private final int msgBoxHint = START;
private final int appendText = START + 1;
Toast mytoast , savetoast;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    Log.d(TAG, "Here 1");
    ipAddress = getLocalIpAddress();
    Log.d(TAG, "Get local IP="+ ipAddress);
    text = (TextView) findViewById(R.id.text);
    ipBox =  (EditText) findViewById(R.id.ipBox);
    serverResponse = (TextView) findViewById(R.id.response);
    portBox =  (EditText) findViewById(R.id.portBox);
    send = (Button) findViewById(R.id.send);
    send.setOnClickListener(buttonsendOnClickListener);      
    connect = (ToggleButton) findViewById(R.id.connect);      
    connect.setOnClickListener(buttonConnectOnClickListener);
    Button buttonExit = (Button) findViewById(R.id.btnExit);
    buttonExit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "Exit");
            Log.d(TAG, "Disconnect" );
            if(client != null)
            {
                try {
                    client.close();
                } catch (IOException e) {
                 Log.d(TAG, "Disconnect"+e.toString() );
                }
            } 
            finish();
        }
    });  
}

OnClickListener buttonConnectOnClickListener = new OnClickListener() {    
/** Manages all button clicks from the screen */
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
public void onClick(View arg0) {
    switch(arg0.getId())
    {
        case R.id.connect:
             if(connect.isChecked())
             {
                 Log.d(TAG, "Connect" );

                 EditText edIP = (EditText) findViewById(R.id.ipBox);
         String ed_textIP = edIP.getText().toString().trim();
         if(ed_textIP.isEmpty() || ed_textIP.length() == 0 || ed_textIP.equals("") || ed_textIP == null )
         {
             Toast.makeText(MainActivity.this, "IP Address or PORT is incorrect", Toast.LENGTH_SHORT).show();
             Log.d(TAG, "IP Address or PORT is incorrect");
         }
                    setValues(R.id.connect,true);
                    setValues(R.id.send,true);
                    setValues(R.id.ipBox,false);
                String tMsg = welcomeMsg.toString();
                MyClientTask myClientTask = new MyClientTask(ipBox
                        .getText().toString(), Integer.parseInt(portBox
                        .getText().toString()),
                        tMsg);


                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                else
                    myClientTask.execute();
             }
             else
             { /*Toast.makeText(this, ipBox.getText(), Toast.LENGTH_LONG).show();*/
                 Log.d(TAG, "Disconnect" );
                 if(client != null)
                 {
                     try {
                         client.close();
                     } catch (IOException e) {
                         Log.d(TAG, "Disconnect"+e.toString() );
                     }

                     setText(R.id.text,"Press the connect button to start the client");
                     setText(msgBoxHint,"");

                     setValues(R.id.connect,false);
                     setValues(R.id.ipBox,true);
                     setValues(R.id.send,false);
                 }   
                 else
                 {
                     setValues(R.id.connect,false);
                 }
             }
             break;
    }
}
}; 

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

    String dstAddress;
    int dstPort;
    String response = "";
    String msgToServer;
    MyClientTask(String addr, int port, String msgTo) {
        dstAddress = addr;
        dstPort = port;
        msgToServer = msgTo;
    }

    protected Void doInBackground(Void... Arg0) {
        Log.d(TAG, "InBackground");
        Socket socket = null;
        DataOutputStream outToServer = null;
        DataInputStream inFromServer = null;

        try {
            client  = new Socket(dstAddress, dstPort);
            outToServer = new DataOutputStream(client.getOutputStream());       
            inFromServer =  new DataInputStream(new BufferedInputStream(client.getInputStream()));  // Input stream <- from server
        }catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            Log.d(TAG, "InBackground 1");
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mytoast =  Toast.makeText(MainActivity.this, "Error UnknownHostException", 
                        Toast.LENGTH_SHORT);
                        mytoast.show();
                        setValues(R.id.send,false);
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                           @Override
                           public void run() {
                               mytoast.cancel(); 
                           }
                    }, 500);                      
                }
            });
        } catch (IOException e) {
            Log.d(TAG, "InBackground 2");
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mytoast =  Toast.makeText(MainActivity.this, "Error IOException", 
                        Toast.LENGTH_SHORT);
                        mytoast.show();
                        setValues(R.id.connect,false);
                        setValues(R.id.send,false);
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                           @Override
                           public void run() {
                               mytoast.cancel(); 
                           }
                    }, 500);

                }
            });
        }finally {
            Log.d(TAG, "InBackground 3");
            if (socket != null) {
                try {
                    socket.close();
                    Log.d(TAG, "InBackground 3.11");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d(TAG, "InBackground 3.12");
                }
            }
            Log.d(TAG, "InBackground 3.1");
        }
        Log.d(TAG, "InBackground 4");
        return null;        
    }
    @Override
    protected void onPostExecute(Void result) {
        serverResponse.setText(response);
        super.onPostExecute(result);
    }
}

OnClickListener buttonsendOnClickListener = new OnClickListener() {    
    /** Manages all button clicks from the screen */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
    public void onClick(View arg0) {
        switch(arg0.getId())
        {
            case R.id.send:
                     Log.d(TAG, "Sent" );
                     String sentence = "Submit";
                     String recieve = "";
                     serverResponse  = (TextView) findViewById(R.id.response);
                     try {
                        outToServer = new DataOutputStream(client.getOutputStream());       
                        inFromServer =  new DataInputStream(new BufferedInputStream(client.getInputStream()));
                         Log.d(TAG, "Sent 1-1" );     
                        if(sentence != null){
                            outToServer.writeUTF(sentence);
                            outToServer.flush();    
                        }

                        /*
                         * 
                         * 
                         * 
                         * 
                         * 
                         */
                        Log.d(TAG, "Sent 1-2"+ recieve);    



                     } catch (IOException e) {
                         setValues(R.id.ipBox,true);
                         setValues(R.id.connect,false);
                         setValues(R.id.send,false);
                     }
                     break;
        }
      }
    }; 

private String getLocalIpAddress() {
    Log.d(TAG, "Here 2");
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    Log.d(TAG, "Here 3");
    WifiInfo info = wifi.getConnectionInfo();
    Log.d(TAG, "Here 4");
    return Formatter.formatIpAddress(info.getIpAddress());
}

private void setText(int view, String content)
{
    switch(view)
    {
        case R.id.ipBox: ipBox.setText(content); break;
        case R.id.text: text.setText(content+"\n\n"); break;
        case appendText: text.append(content+"\n\n"); break;
    }
}

private void setValues(int view, boolean value)
{
    switch(view)
    {
        case R.id.ipBox: ipBox.setEnabled(value); break;
        case R.id.send: send.setEnabled(value); break;
        case R.id.connect: connect.setChecked(value); break;
    }
}    
}

我想,我必须在buttonsendOnClickListener附近的/*****/.

添加接收代码

1 个答案:

答案 0 :(得分:0)

Do not work with sockets in main (gui) thread. Use AsyncTask!
Android fails if work with sockets in main (gui) thread.

Example:

    new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // do in main thread before
            }

            @Override
            protected Void doInBackground(Void... v) {
                // do in thread, use sockets

                return null;
            }

            @Override
            protected void onPostExecute(Void v) {
                super.onPostExecute(integer);
                // do in main thread after
            }
        }.execute();  

Learn about AsyncTask advance.

相关问题