通过Android中的套接字接收消息

时间:2019-07-20 14:59:39

标签: android-studio

我试图使用'connection'类在按钮上建立套接字连接,并使用'messagesender'类在按钮上发送消息。我已经创建了一个名为“ messagereceiver”的类,我想在创建套接字到套接字终止(按钮事件终止)之后使用此类接收消息。我对创建“ messagereceiver”类的对象感到困惑,我应该在哪里创建它的对象,以便我可以在套接字的整个生命周期中接收消息。

public class MainActivity extends AppCompatActivity {

    static Socket s;
    Button conn;
    EditText mesg;
    EditText ip;
    EditText port;
    Button send;
    Button close;
    static PrintWriter PW;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        conn = (Button) findViewById(R.id.button);
        send = (Button) findViewById(R.id.button2);
        close = (Button)findViewById(R.id.button3);
        mesg = (EditText)findViewById(R.id.editText);
        ip = (EditText)findViewById(R.id.editText2);
        port = (EditText)findViewById(R.id.editText3);

        ip.setText("");
        port.setText("0");

        mesg.setVisibility(View.INVISIBLE);
        close.setVisibility(View.INVISIBLE);
        send.setVisibility(View.INVISIBLE);



    }
    public final boolean isInternetOn() {

        // get Connectivity Manager object to check connection
        ConnectivityManager connec =
                (ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

        // Check for network connections
        if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo
                .State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {

            // if connected with internet

           // Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
            return true;

        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {

            //Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
            return false;
        }
        return false;
    }

    public void conn(View v) {

        if (isInternetOn()==true) {
            final String IP = ip.getText().toString();
            final int PORT = Integer.parseInt(port.getText().toString()) ;

           connection c = new connection(IP, PORT);

            c.execute();
            mesg.setVisibility(View.VISIBLE);
            close.setVisibility(View.VISIBLE);
            send.setVisibility(View.VISIBLE);

            ip.setVisibility(View.INVISIBLE);
            port.setVisibility(View.INVISIBLE);
            conn.setVisibility(View.INVISIBLE);
        }
        else
            Toast.makeText(getApplicationContext(),"Please Check Your Internet Connection",Toast.LENGTH_LONG).show();


    }
    public void sendmsg(View v){


        messagesender ms = new messagesender();
        String ss = mesg.getText().toString();
        mesg.setText("");
        ms.execute(ss);
    }
    public void close(View v){
        try {
            PW.close();
            s.close();
            conn.setVisibility(View.VISIBLE);
            ip.setVisibility(View.VISIBLE);
            port.setVisibility(View.VISIBLE);

            mesg.setVisibility(View.INVISIBLE);
            send.setVisibility(View.INVISIBLE);
            close.setVisibility(View.INVISIBLE);
            if (s.isClosed()){
                Toast.makeText(getApplicationContext(),"Socket is closed",Toast.LENGTH_LONG).show();
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }


    }

    class connection extends AsyncTask<String, Integer, Boolean> {
        final String i;
        int p;

        public connection(String i, int p) {
            this.i = i;
            this.p = p;
        }

        @Override
        protected Boolean doInBackground (String...args) {
            try {
                s = new Socket(i,p);

                System.out.println("connected!");
            } catch (IOException e) {
                System.out.println(e);
            }
            return s.isConnected();
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            if(s.isConnected())
            {
                Toast.makeText(getApplicationContext(),"Socket is connected",Toast.LENGTH_LONG).show();
                conn.setVisibility(View.INVISIBLE);

            }
            else
                Toast.makeText(getApplicationContext(),"Socket is not connected",Toast.LENGTH_LONG).show();
        }

    }

    private static class messagesender extends AsyncTask<String,Void,Void>{
        @Override
        protected Void doInBackground(String... Voids) {
            String msg = Voids[0];
            try {

                if(s.isConnected()) {
                    PW = new PrintWriter(s.getOutputStream());
                    PW.write(msg+"\n");
                    PW.flush();
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
            return null;
        }
    }

    public class messagereceiver extends AsyncTask<String,Void,Void>{

        InputStreamReader isr;
        String msg ;
        BufferedReader br ;
        Handler h = new Handler();
        @Override
        protected Void doInBackground(String... Voids) {
            try {
                if(s.isConnected()) {
                    isr = new InputStreamReader(s.getInputStream());
                    br = new BufferedReader(isr);
                    msg = br.readLine();
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "Message:" + msg, Toast.LENGTH_LONG).show();
                        }
                    });
            }}
            catch (IOException e){
                e.printStackTrace();
            }
            return null;
        }
    }
}

0 个答案:

没有答案