从Android中的TCP cliant接收数据

时间:2019-04-13 15:05:53

标签: android tcp tcpclient

我可以将数据发送到服务器,但不能接收数据。

如何从服务器获取数据。我使用Golang服务器。服务器向我发送了邮件,但我什么也收不到。我认为TcpClient或ConnectTask类中的run Function出错。我也在清单中添加了Internt权限。

这是我的mainActivity:

public class MainActivity extends AppCompatActivity {
    TcpClient mTcpClient;
    Button send;
    TextView txt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        send= (Button)findViewById(R.id.send);
        txt= (TextView) findViewById(R.id.txt);

         new ConnectTask().execute("");
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txt.setText(show);
                String message="hhhhhhhhhhhhh";
                if (mTcpClient != null)
                {
                    mTcpClient.sendMessage(message);

                }


            }
        });

    }
    ///////////////////  class    ////////////////

    public class ConnectTask extends AsyncTask<String, String, TcpClient> {

        @Override
        protected TcpClient doInBackground(String... message) {


            //we create a TCPClient object
            mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
                @Override
                //here the messageReceived method is implemented
                public void messageReceived(String message) {
                    //this method calls the onProgressUpdate
                    Toast.makeText(getApplicationContext() ,"NO Message", Toast.LENGTH_LONG).show();
                    publishProgress(message);

                }
            });
            mTcpClient.run();
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            txt.setText(values[0] );
        }//onProgressUpdate
    }//ConnectTask
}//class

还有我的TcpClient类:

public class TcpClient {

    public static final String TAG = TcpClient.class.getSimpleName();
    public static final String SERVER_IP = "192.168.1.2"; //server IP address
    public static final int SERVER_PORT = 37533;
    // message to send to the server
    private String mServerMessage;
    // sends message received notifications
    private OnMessageReceived mMessageListener = null;
    // while this is true, the server will continue running
    private boolean mRun = false;
    // used to send messages
    private PrintWriter mBufferOut;
    // used to read messages from the server
    private BufferedReader mBufferIn;
    private InetAddress serverAddr;
    private Socket socket;

    public TcpClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    public void sendMessage(final String message) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (mBufferOut != null) {
                    mBufferOut.println(message);
                    mBufferOut.flush();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
    public void stopClient() {

        mRun = false;
        if (mBufferOut != null) {
            mBufferOut.flush();
            mBufferOut.close();
        }
        mMessageListener = null;
        mBufferIn = null;
        mBufferOut = null;
        mServerMessage = null;
    }

    public void run() {

        mRun = true;

        try {
             serverAddr = InetAddress.getByName(SERVER_IP);
             socket     = new Socket(serverAddr, SERVER_PORT);
            try {
                mBufferOut = new PrintWriter(socket.getOutputStream());

                mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                int charsRead = 0;
                char[] buffer = new char[2048]; //choose your buffer size if you need other than 1024
                charsRead      = mBufferIn.read(buffer);
                mServerMessage = new String(buffer).substring(0, charsRead);

                while (mRun)
                {
                    if (mServerMessage != null && mMessageListener != null)
                    {
                        mMessageListener.messageReceived(mServerMessage);
                    }
                    mServerMessage = null;
                }
            } catch (Exception e) {
            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }

        } catch (Exception e) {

        }

    }
    //Declare the interface. The method messageReceived(String message) will must be implemented in the Activity
    //class at on AsyncTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}//class TcpClient

0 个答案:

没有答案