繁体   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