当前位置:   article > 正文

Android与JavaIO实现简单Echo服务器与客户端_android程序echo

android程序echo

温习旧知识,巩固基础,同时还能有新的收货。

古人云:温故而知新,可以为师矣。

那就分享出来一起学习吧。


服务端,纯Java实现:

  1. public class EchoServer {
  2. public static void main(String args[]) {
  3. try {
  4. ServerSocket serverSocket = new ServerSocket(8999);
  5. while (true) { //直接在主线程做了,不另起线程了
  6. Socket socket = serverSocket.accept();
  7. System.out.println("connected from:" + socket.getInetAddress());
  8. new SocketThread(socket).start();
  9. }
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. private static class SocketThread extends Thread {
  15. private Socket mSocket;
  16. public SocketThread(Socket socket) {
  17. this.mSocket = socket;
  18. }
  19. @Override
  20. public void run() {
  21. BufferedReader br = null;
  22. PrintWriter pw = null;
  23. try {
  24. br = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
  25. pw = new PrintWriter(new OutputStreamWriter(mSocket.getOutputStream()));
  26. String line;
  27. while (true) {
  28. line = br.readLine();
  29. System.out.println("received:" + line + " from:" + mSocket.getInetAddress());
  30. String result = "response: " + line + "\n"; //我们用的都是readLine方法读取,所以加入换行符,代表结尾
  31. pw.print(result);
  32. pw.flush();
  33. }
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. } finally {
  37. if (br != null) {
  38. try {
  39. br.close();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. if (pw != null) {
  45. pw.close();
  46. }
  47. if (mSocket != null && !mSocket.isClosed()) {
  48. try {
  49. mSocket.close();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }

Android客户端:

  1. public class MainActivity extends AppCompatActivity {
  2. private EditText mIpEt;
  3. private EditText mPortEt;
  4. private Button mConnBtn;
  5. private TextView mScreenTv;
  6. private EditText mInputEt;
  7. private Button mSendBtn;
  8. private SocketThread mSocketThread;
  9. private static Handler mMainHandler;
  10. private static final int MSG_CONNECT = 0x001;
  11. private static final int MSG_RECEIVE = 0x002;
  12. private static final String DATA_RECEIVE = "data_receive";
  13. @Override
  14. protected void onCreate(@Nullable Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.activity_main);
  17. mIpEt = findViewById(R.id.main_ip_et);
  18. mPortEt = findViewById(R.id.main_port_et);
  19. mConnBtn = findViewById(R.id.main_connect_btn);
  20. mScreenTv = findViewById(R.id.main_screen_tv);
  21. mInputEt = findViewById(R.id.main_input_et);
  22. mSendBtn = findViewById(R.id.main_send_btn);
  23. // defalut value. Change it to your own server ip
  24. mIpEt.setText("192.168.1.1");
  25. mPortEt.setText("8999");
  26. mConnBtn.setOnClickListener(new View.OnClickListener() {
  27. @Override
  28. public void onClick(View v) {
  29. String ip = mIpEt.getText().toString();
  30. String port = mPortEt.getText().toString();
  31. if (TextUtils.isEmpty(ip) || TextUtils.isEmpty(port)) {
  32. Toast.makeText(MainActivity.this, "ip or port is null", Toast.LENGTH_SHORT).show();
  33. } else {
  34. connectToServer(ip, Integer.valueOf(port));
  35. }
  36. }
  37. });
  38. mSendBtn.setOnClickListener(new View.OnClickListener() {
  39. @Override
  40. public void onClick(View v) {
  41. String data = mInputEt.getText().toString();
  42. if (!TextUtils.isEmpty(data)) {
  43. mSocketThread.sendMsgToServer(data + "\n"); //我们用的都是readLine方法读取,所以加入换行符,代表结尾
  44. }
  45. }
  46. });
  47. // TODO handler may cause memory leaks
  48. mMainHandler = new Handler() {
  49. @Override
  50. public void handleMessage(Message msg) {
  51. switch (msg.what) {
  52. case MSG_CONNECT:
  53. Toast.makeText(MainActivity.this, "Connect to Server Success", Toast.LENGTH_SHORT).show();
  54. mConnBtn.setText("Connected");
  55. mConnBtn.setEnabled(false);
  56. break;
  57. case MSG_RECEIVE:
  58. Bundle data = msg.getData();
  59. String dataStr = data.getString(DATA_RECEIVE);
  60. CharSequence originData = mScreenTv.getText();
  61. String result = originData + "\n" + dataStr;
  62. mScreenTv.setText(result);
  63. break;
  64. }
  65. }
  66. };
  67. }
  68. private void connectToServer(String ip, int port) {
  69. mSocketThread = new SocketThread(ip, port);
  70. mSocketThread.start();
  71. }
  1. // 程序简单,直接写静态内部类来实现了
  2. private static class SocketThread extends Thread {
  3. private Socket mSocket;
  4. private String mIp;
  5. private int mPort;
  6. private InputStream mInputStream;
  7. private BufferedReader mBufferedReader;
  8. private PrintWriter mPrintWriter;
  9. public SocketThread(String ip, int port) {
  10. this.mIp = ip;
  11. this.mPort = port;
  12. }
  13. @Override
  14. public void run() {
  15. try {
  16. mSocket = new Socket(mIp, mPort);
  17. mMainHandler.sendEmptyMessage(MSG_CONNECT);
  18. // init i/o stream
  19. mInputStream = mSocket.getInputStream();
  20. mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream));
  21. OutputStream outputStream = mSocket.getOutputStream();
  22. mPrintWriter = new PrintWriter(outputStream);
  23. String line;
  24. while (true) {
  25. line = mBufferedReader.readLine();
  26. Message message = mMainHandler.obtainMessage();
  27. message.what = MSG_RECEIVE;
  28. Bundle data = new Bundle();
  29. data.putString(DATA_RECEIVE, line);
  30. message.setData(data);
  31. mMainHandler.sendMessage(message);
  32. }
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. } finally {
  36. if (mBufferedReader != null) {
  37. try {
  38. mBufferedReader.close();
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. if (mInputStream != null) {
  44. try {
  45. mInputStream.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. if (mPrintWriter != null) {
  51. mPrintWriter.close();
  52. }
  53. if (mSocket != null && !mSocket.isClosed()) {
  54. try {
  55. mSocket.close();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. }
  61. }
  62. public void sendMsgToServer(final String data) {
  63. new Thread(new Runnable() {
  64. @Override
  65. public void run() {
  66. mPrintWriter.print(data);
  67. mPrintWriter.flush();
  68. }
  69. }).start();
  70. }
  71. }
  72. }

MainActivity的布局文件。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical"
  6. android:layout_margin="15dp">
  7. <EditText
  8. android:id="@+id/main_ip_et"
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:hint="ip address"/>
  12. <EditText
  13. android:id="@+id/main_port_et"
  14. android:layout_width="match_parent"
  15. android:layout_height="wrap_content"
  16. android:hint="port"
  17. android:inputType="number"/>
  18. <Button
  19. android:id="@+id/main_connect_btn"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_gravity="center"
  23. android:text="Connect"/>
  24. <EditText
  25. android:id="@+id/main_input_et"
  26. android:layout_width="match_parent"
  27. android:layout_height="wrap_content"
  28. android:hint="message to server"/>
  29. <Button
  30. android:id="@+id/main_send_btn"
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:layout_gravity="center"
  34. android:text="Send"/>
  35. <ScrollView
  36. android:layout_width="match_parent"
  37. android:layout_height="match_parent"
  38. android:layout_marginTop="10dp">
  39. <TextView
  40. android:id="@+id/main_screen_tv"
  41. android:layout_width="match_parent"
  42. android:layout_height="wrap_content"
  43. android:text="received message will be shown here"/>
  44. </ScrollView>
  45. </LinearLayout>
最后别忘了Android客户端里声明网络权限。

其他就没有什么特别要注意的点了,直接跑起来吧~


客户端运行



服务端日志

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/160706
推荐阅读
相关标签
  

闽ICP备14008679号