从Android客户端连接到TCP协议

时间:2016-04-19 10:26:23

标签: android sockets tcp

我正在寻找答案,我希望有人可以帮助我并指导我解决问题。

我想要的是是从android设备连接到tcp协议服务器以交换一些消息。

我拥有的是我使用了Github上找到的一些例子

我已经将连接ip修改为我的连接。我成功地设法连接到服务器。我从服务器得到了回复,例如:

<?xml version="1.0" encoding="UTF-8"?>
 <Messages>
    <Connection>Accepted</Connection>
 </Messages>

和logcat显示:

net.stackueberflow.netcat I/NetCat TCP Client activity: host: 192.168.170.90, port: 3000
net.stackueberflow.netcat I/NetCat TCP Client activity: onPreExecute
net.stackueberflow.netcat I/NetCat TCP Client activity: doInBackground: Creating socket
net.stackueberflow.netcat I/AsyncTask: doInBackground: Socket created, streams assigned
net.stackueberflow.netcat I/AsyncTask: doInBackground: Waiting for inital data...
net.stackueberflow.netcat I/NetCat TCP Client activity: doInBackground: Got some data
net.stackueberflow.netcat I/NetCat TCP Client activity: onProgressUpdate: 100 bytes received.

需要什么

连接后出现问题。当我尝试发送一些东西时,我在logcat上得到这个并且没有显示输出。只有我输入的消息字符串没有任何响应。 Logcat显示:

net.stackueberflow.netcat D/NetCat TCP Client activity: SendDataToNetwork: Writing received message to socket

没有更多的事情发生。所以我不断发送消息而没有任何回复。

任何帮助我都会非常感激!

编辑#1

package net.stackueberflow.netcat;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

// TODO: Handle not connected

public class TCPClientActivity extends Activity {
    private static final String TAG = "NetCat TCP Client activity";
    private TextView tv;
    private EditText input;
    private String host;
    private int port;
    private byte[] fileBytes = null;
    private Uri uri;
    private TCPClientTask networkTask;

 /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connected);

    tv = (TextView)findViewById(R.id.output);
    input = (EditText)findViewById(R.id.input);

    Intent i = getIntent();
    host = i.getStringExtra("host");
    port = i.getIntExtra("port", 3000);


    if ( (uri = (Uri)i.getParcelableExtra(Intent.EXTRA_STREAM)) != null) {
        Log.i(TAG, "received file uri: "+uri.toString());
        try {
            fileBytes = IOHelpers.readFile(new File(IOHelpers.getRealPathFromURI(uri, this)));
            input.setFocusable(false);
            input.setHint("Sending file "+IOHelpers.getRealPathFromURI(uri, this));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    Log.i(TAG, "host: "+host+", port: "+port);


    Button button = (Button)findViewById(R.id.button1);
    networkTask = new TCPClientTask();
    networkTask.execute();

    input.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                (keyCode == KeyEvent.KEYCODE_ENTER)) {
              // Perform action on key press
                send();
              return true;
            }
            return false;
        }
    });

    button.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            send();
        }
    });
}

@Override 
public void onPause() {
    super.onPause();
    if (networkTask != null)
        networkTask.cancel(true);
}


private void send() {
    if (fileBytes != null)
        sendBlobTCP(uri);
    else {
        input.setText("" +
                "<Login>\n" +
                "  <Username>admin</Username>\n" +
                "  <Password>admin</Password>\n" +
                "</Login>\n");
        String str = input.getText().toString();
        networkTask.SendDataToNetwork(str.getBytes());
        input.setText("");
        appendToOutput(str);

    }
}

private void sendBlobTCP(Uri uri) {
    networkTask.SendDataToNetwork(fileBytes);
    tv.append("\nSending File "+IOHelpers.getRealPathFromURI(uri, this));
}

private void appendToOutput(String str) {
    tv.append(str);
    tv.setMovementMethod(new ScrollingMovementMethod());
}

private void appendToOutput(byte[] data) {
    String str;
    try {
        str = new String(data, "UTF8");
        appendToOutput(str);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


private class TCPClientTask extends AsyncTask<Void, byte[], Boolean> {
    Socket socket; //Network Socket
    InputStream is; //Network Input Stream
    OutputStream os; //Network Output Stream
    byte[] buffer = new byte[4096];

    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute");
    }

    @Override
    protected Boolean doInBackground(Void... params) { //This runs on a different thread
        boolean result = false;
        try {
            // Connect to address
            Log.i(TAG, "doInBackground: Creating socket");
            SocketAddress sockaddr = new InetSocketAddress(host, port);
            socket = new Socket();
            socket.connect(sockaddr, 5000); //10 second connection timeout
            if (socket.isConnected()) {
                is = socket.getInputStream();
                os = socket.getOutputStream();
                Log.i("AsyncTask", "doInBackground: Socket created, streams assigned");
                Log.i("AsyncTask", "doInBackground: Waiting for inital data...");
                int read;
                //This is blocking
                while((read = is.read(buffer, 0, 4096)) > 0 ) {
                    byte[] tempdata = new byte[read];
                    System.arraycopy(buffer, 0, tempdata, 0, read);
                    publishProgress(tempdata);
                    Log.i(TAG, "doInBackground: Got some data");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.i(TAG, "doInBackground: IOException");
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            Log.i(TAG, "doInBackground: Exception");
            result = true;
        } finally {
            try {
                is.close();
                os.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.i(TAG, "doInBackground: Finished");
        }
        return result;
    }

    public boolean SendDataToNetwork(final byte[] cmd) { //You run this from the main thread.
        // Wait until socket is open and ready to use

        if (socket.isConnected()) {
            Log.d(TAG, "SendDataToNetwork: Writing received message to socket");
            new Thread(new Runnable() {
                public void run() {
                    try {
                        os.write(cmd);
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        Log.i(TAG, "SendDataToNetwork: Message send failed. Caught an exception");
                    }
                }
            }
                    ).start();
            return true;
        }
        else
            Log.i(TAG, "SendDataToNetwork: Cannot send message. Socket is closed");

        return false;
    }

    @Override
    protected void onProgressUpdate(byte[]... values) {
        if (values.length > 0) {
            Log.i(TAG, "onProgressUpdate: " + values[0].length + " bytes received.");
            appendToOutput(buffer);
        }
    }

    @Override
    protected void onCancelled() {
        Log.i(TAG, "Cancelled.");
    }
    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            Log.i(TAG, "onPostExecute: Completed with an Error.");

        } else {
            Log.i(TAG, "onPostExecute: Completed.");
        }
    }
    }
}

1 个答案:

答案 0 :(得分:0)

我的解决方案的答案是我需要通过EOT命令结束事务。在java中是:

"/4" 

这解决了我的问题