1. 注意
  2. 代码

Android作为客户端(client)对服务器(server)进行request操作,并从服务器中得到response。

这里主要使用socket来进行数据传输。

注意

  • 若SDK version > 9,则需要加入

    1
    2
    3
    4
    if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }

    否则会有Error: SocketException: socket failed: EACCES (Permission denied).

  • socket的相关操作不能放在UI线程中,否则会有Error: android.os.NetworkOnMainThreadException

代码

在activity_main.xml中加了一个用于用户输入消息的editText,一个发送消息的button,一个显示接收消息的textView。

发送与接收数据可以是string,也可以是object。

若是object的话记得类要implements java.io.Serializable

  • MainActivity.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.os.StrictMode;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.EditText;
    import android.widget.TextView;

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.lang.ref.WeakReference;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.util.ArrayList;

    public class MainActivity extends Activity {
    public static final String HOST = "10.0.2.2";
    public static final int PORT = 12345;
    public final MyHandler mHandler = new MyHandler(this);
    public EditText mEditText = null;
    public TextView mTextView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }
    mEditText = (EditText) findViewById(R.id.editText);
    mTextView = (TextView) findViewById(R.id.textView);
    findViewById(R.id.button).setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    Message message = mHandler.obtainMessage();
    message.what = 1;
    mHandler.sendMessage(message);
    }
    });
    }

    public static class MyHandler extends Handler {
    private final WeakReference<MainActivity> mActivity;

    public MyHandler(MainActivity activity) {
    mActivity = new WeakReference<>(activity);
    }

    public void sendString(MainActivity activity) {
    Socket socket = null;
    try {
    socket = new Socket(InetAddress.getByName(HOST), PORT);
    // send message
    String request = activity.mEditText.getText().toString() + "\n";
    PrintWriter out = new PrintWriter(new BufferedWriter(
    new OutputStreamWriter(socket.getOutputStream())),
    true);
    out.write(request);
    out.flush();

    // receive message
    BufferedReader in = new BufferedReader(
    new InputStreamReader(socket.getInputStream()));
    String response = in.readLine();
    activity.mTextView.setText(response);

    out.close();
    in.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    try {
    if (socket != null) {
    socket.close();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public void sendObject(MainActivity activity) {
    Socket socket = null;
    try {
    socket = new Socket(InetAddress.getByName(HOST), PORT);
    // send object
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    ArrayList<Point> points = new ArrayList<>();
    points.add(new Point(-3, 3.14));
    out.writeObject(points);
    out.flush();

    // receive object
    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
    Object obj = in.readObject();
    points = (ArrayList<Point>) obj;
    activity.mTextView.setText(points.toString());

    out.close();
    in.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    try {
    if (socket != null) {
    socket.close();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public void handleMessage(Message msg) {
    MainActivity activity = mActivity.get();
    if (activity != null) {
    switch (msg.what) {
    case 0:
    sendString(activity);
    break;
    case 1:
    sendObject(activity);
    break;
    }
    }
    }
    }
    }

  • Point.java

    1
    2
    3
    4
    5
    6
    7
    8
    public class Point implements java.io.Serializable {
    public double x, y;

    public Point(double x, double y) {
    this.x = x;
    this.y = y;
    }
    }