简体   繁体   中英

Java TCP Echo Client and Server in one App

I am trying to build an application where I can Echo between two android devices. I want them to act as both a client and a server.

I have the following Client-side code:

public class MainActivity extends Activity {
/** Called when the activity is first created. */
    private EditText portNumber;
    private EditText hostName;
    private EditText inputMsg;
    private EditText resultMsg;
    private InetAddress ia;
    private Socket mySocket;
    private InputStream isIn;
    private OutputStream psOut;
    private byte abIn[];
    private String sHostName;
    private int iPortNumber;
    private Handler mHandler;
    private int iNumRead;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    hostName = (EditText) findViewById(R.id.editText1);
    portNumber = (EditText) findViewById(R.id.editText2);
    resultMsg = (EditText) findViewById(R.id.editText3);
    inputMsg = (EditText) findViewById(R.id.editText4);
    mHandler= new Handler();

}

class ClientThread implements Runnable {
    @Override
    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(sHostName);
            try {
                mySocket = new Socket(serverAddr, iPortNumber);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        catch (UnknownHostException e1)
        {
            e1.printStackTrace();
        }

    }
}
class ResponseThread implements Runnable {

    @Override

    public void run() {
        try {
            isIn = mySocket.getInputStream();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        iNumRead = 0;
        abIn = new byte[1024];


        try {
            iNumRead = isIn.read(abIn);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        mHandler.post(new Runnable(){
            public void run(){
                String sResponse, sTemp;

                sTemp = new String(abIn, 0, iNumRead);
                sResponse = "We got back: " + sTemp;
                resultMsg.setText(sResponse);

            }

        });

    }
}

public void myEchoHandler(View view) {
    switch (view.getId()) {
        case R.id.button1:          /* This is the connect button */
            sHostName = hostName.getText().toString();
            iPortNumber = Integer.parseInt(portNumber.getText().toString());


            new Thread(new ClientThread()).start();


            break;
        case R.id.button2:    /* This is the send data button */

            byte[] sInputMsg = inputMsg.getText().toString().getBytes();
            try  {
                psOut = mySocket.getOutputStream();
                psOut.write(sInputMsg,0, sInputMsg.length);
                new Thread(new ResponseThread()).start();

            }
            catch (Exception ex) {
                Toast.makeText(this,"Send data failed.  Exception" + ex + "\n",  Toast.LENGTH_LONG).show();
            }



            break;
        case R.id.button3:   // This is the quit button.
            String sTemp2;
            try {
                mySocket.close();
                inputMsg.setText("");
                sTemp2 = new String ("Goodbye ...");
                resultMsg.setText(sTemp2);
            }
            catch (Exception ex)
            {
                Toast.makeText(this,"Close socket failed.  Exception " + ex + "\n", Toast.LENGTH_LONG).show();
            }
    } //end of switch
}//end of myEchoHandler




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

And the following Server-side code:

public class TCPEchoServer {
// define a constant used as size of buffer
static final int BUFSIZE=1024;
// main starts things rolling
static public void main(String args[]) {
    if (args.length != 1) {
        throw new IllegalArgumentException("Must specify a port!");
    }
    int port = Integer.parseInt(args[0]);
    try {
// Create Server Socket (passive socket)
        ServerSocket ss = new ServerSocket(port);
        while (true) {
            Socket s = ss.accept();
            handleClient(s);
        }
    } catch (IOException e) {
        System.out.println("Fatal I/O Error !");
        System.exit(0);
    }
}
    static void handleClient(Socket s) throws IOException {
    byte[] buff = new byte[BUFSIZE];
    int bytesread = 0;
// print out client's address
    System.out.println("Connection from " +
            s.getInetAddress().getHostAddress());
// Set up streams
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
// read/write loop
    while ((bytesread = in.read(buff)) != -1) {
        out.write(buff,0,bytesread);
    }
    System.out.println("Client has left\n");
    s.close();
}
}

Any suggestions on how I could proceed? I was thinking of creating the app with two classes, one for the client-side code and one for the server-side code.

You could always create two classes that run on different threads, but I will advise against that as I think you are not looking something that sophisticated.

What is the purpose of the communication between these 2 android devices? You can simply define one of them as the server and the other as the client and they would be able to communicate easily like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM