簡體   English   中英

一個應用程序中的Java TCP Echo客戶端和服務器

[英]Java TCP Echo Client and Server in one App

我正在嘗試構建一個我可以在兩個Android設備之間回顯的應用程序。 我希望他們同時充當客戶端和服務器。

我有以下客戶端代碼:

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;
}

}

以及以下服務器端代碼:

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();
}
}

關於如何進行的任何建議? 我當時正在考慮用兩個類創建應用程序,一個用於客戶端代碼,一個用於服務器端代碼。

您總是可以創建兩個在不同線程上運行的類,但是我建議您不要這樣做,因為我認為您看起來並不復雜。

這兩個android設備之間進行通信的目的是什么? 您可以簡單地將其中一個定義為服務器,將另一個定義為客戶端,這樣它們就可以輕松進行通信。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM