[关闭]
@linux1s1s 2017-01-22T17:18:41.000000Z 字数 5609 阅读 2486

Android Socket

AndroidHttp 2015-05


客户端编程步骤:

1: 创建客户端套接字(指定服务器端IP地址与端口号)
2: 连接(Android 创建Socket时会自动连接)
3: 与服务器端进行通信
4: 关闭套接字

  1. 客户端先建立连接后先获得输出流,然后再获得输入流。不然活有EOFException的异常。
  2. 中间的管道连接是通过InputStream/OutputStream流实现的。
  3. 一旦管道建立起来可进行通信 。
  4. 关闭管道的同时意味着关闭Socket 。
  5. 当对同一个Socket创建重复管道时会异常。
  1. try {
  2. //连接服务器 并设置连接超时为5秒
  3. socket = new Socket();
  4. socket.connect(new InetSocketAddress("1.1.9.30", 30000), 5000);
  5. //先获取输出流
  6. OutputStream ou = socket.getOutputStream();
  7. //再获取输入流
  8. BufferedReader bff = new BufferedReader(new InputStreamReader(
  9. socket.getInputStream()));
  10. //读取发来服务器信息
  11. String line = null;
  12. buffer="";
  13. while ((line = bff.readLine()) != null) {
  14. buffer = line + buffer;
  15. }
  16. //向输出流写入信息,即向服务器发送信息
  17. ou.write("android 客户端".getBytes("gbk"));
  18. ou.flush();
  19. bundle.putString("msg", buffer.toString());
  20. msg.setData(bundle);
  21. //发送消息 修改UI线程中的组件
  22. myHandler.sendMessage(msg);
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }finally
  26. {
  27. //关闭各种输入输出流以及套接字
  28. bff.close();
  29. ou.close();
  30. socket.close();
  31. }

服务器端编程步骤:

1: 创建服务器端套接字并绑定到一个端口上(0-1023是系统预留的,最好大约1024)
2: 套接字设置监听模式等待连接请求
3: 接受连接请求后进行通信
4: 返回,等待赢一个连接请求

  1. 服务器端首先得到输入流,然后将输入流信息输出到其各个客户端
  2. 中间的管道连接是通过InputStream/OutputStream流实现的。
  3. 一旦管道建立起来可进行通信 。
  4. 关闭管道的同时意味着关闭Socket 。
  5. 当对同一个Socket创建重复管道时会异常。
  1. public class AndroidService {
  2. public static void main(String[] args) throws IOException {
  3. ServerSocket serivce = new ServerSocket(30000);
  4. while (true) {
  5. //等待客户端连接
  6. Socket socket = serivce.accept();
  7. new Thread(new AndroidRunable(socket)).start();
  8. }
  9. }
  10. }
  1. String str = "hello world!";
  2. try {
  3. // 首先得到输入流,将输入流读入内存
  4. input = socket.getInputStream();
  5. BufferedReader bff = new BufferedReader(
  6. new InputStreamReader(input));
  7. //然后再向客户端发送信息
  8. output = socket.getOutputStream();
  9. output.write(str.getBytes("gbk"));
  10. output.flush();
  11. //半关闭socket
  12. socket.shutdownOutput();
  13. //获取客户端的信息
  14. while ((line = bff.readLine()) != null) {
  15. System.out.print(line); //这里仅仅是测试使用的,接收到客户端的信息打印出来,有点无聊\(^o^)/~
  16. }
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. finally
  21. {
  22. //关闭各种输入输出流以及套接字
  23. output.close();
  24. bff.close();
  25. input.close();
  26. socket.close();
  27. }

客户端Demo

  1. public class SocketActivity extends Activity {
  2. EditText editText = null;
  3. Button sendButton = null;
  4. TextView display = null;
  5. Socket client = null;
  6. MyHandler myHandler;
  7. DataOutputStream dout;
  8. DataInputStream din;
  9. public void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.clientsocket);
  12. editText = (EditText) findViewById(R.id.message);
  13. sendButton = (Button) findViewById(R.id.send);
  14. display = (TextView) findViewById(R.id.display);
  15. sendButton.setOnClickListener(listener);
  16. try {
  17. client = new Socket("192.168.0.120", 50003);
  18. dout = new DataOutputStream(client.getOutputStream());
  19. din = new DataInputStream(client.getInputStream());
  20. } catch (UnknownHostException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. } catch (IOException e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. }
  27. myHandler = new MyHandler();
  28. MyThread m = new MyThread();
  29. m.start();
  30. }
  31. class MyHandler extends Handler {
  32. public MyHandler() {
  33. }
  34. // 子类必须重写此方法,接受数据
  35. @Override
  36. public void handleMessage(Message msg) {
  37. // TODO Auto-generated method stub
  38. Log.d("MyHandler", "handleMessage......");
  39. super.handleMessage(msg);
  40. // 此处可以更新UI
  41. if (client != null && client.isConnected()) {
  42. Log.i("handler..", "*-----*");
  43. try {
  44. dout.writeUTF("connect...");
  45. String message = din.readUTF();
  46. if (!message.equals(""))
  47. display.setText(display.getText().toString() + "\n"
  48. + "服务器发来的消息--:" + message);
  49. } catch (IOException e) {
  50. // TODO Auto-generated catch block
  51. e.printStackTrace();
  52. }
  53. }
  54. }
  55. }
  56. class MyThread extends Thread {
  57. public void run() {
  58. while (true) {
  59. try {
  60. Thread.sleep(1000);
  61. } catch (InterruptedException e) {
  62. // TODO Auto-generated catch block
  63. e.printStackTrace();
  64. }
  65. Message msg = new Message();
  66. SocketActivity.this.myHandler.sendMessage(msg);
  67. }
  68. }
  69. }
  70. OnClickListener listener = new OnClickListener() {
  71. @Override
  72. public void onClick(View v) {
  73. // TODO Auto-generated method stub
  74. String sendText = editText.getText().toString();
  75. try {
  76. // din = new DataInputStream(client.getInputStream());
  77. dout.writeUTF(sendText);
  78. /*
  79. * display.setText(display.getText().toString() + "\n" +
  80. * "服务器发来的消息:" + din.readUTF());
  81. */
  82. /*
  83. * display.setText(display.getText().toString() + "\n" +
  84. * "服务器发来的消息--:" + din.readUTF());
  85. */
  86. } catch (UnknownHostException e) {
  87. // TODO Auto-generated catch block
  88. e.printStackTrace();
  89. } catch (IOException e) {
  90. // TODO Auto-generated catch block
  91. e.printStackTrace();
  92. }
  93. }
  94. };
  95. }

服务器Demo

  1. public class Server {
  2. static ServerSocket aServerSocket = null; // Server Socet.
  3. DataInputStream aDataInput = null; // Server input Stream that to
  4. // receive msg from client.
  5. DataOutputStream aDataOutput = null; // Server output Stream that to
  6. static ArrayList list = new ArrayList();
  7. public static void main(String[] args) {
  8. try {
  9. aServerSocket = new ServerSocket(50003); // listen 8888 port.
  10. System.out.println("already listen 50003 port.");
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. }
  14. int num = 0;
  15. while (num < 10) {
  16. Socket aSessionSoket = null;
  17. try {
  18. aSessionSoket = aServerSocket.accept();
  19. MyThread thread = new Server().new MyThread(aSessionSoket);
  20. thread.start();
  21. num = list.size();
  22. } catch (IOException e1) {
  23. // TODO Auto-generated catch block
  24. e1.printStackTrace();
  25. }
  26. }
  27. }
  28. class MyThread extends Thread {
  29. Socket aSessionSoket = null;
  30. public MyThread(Socket socket) {
  31. aSessionSoket = socket;
  32. }
  33. public void run() {
  34. try {
  35. aDataInput = new DataInputStream(aSessionSoket.getInputStream());
  36. aDataOutput = new DataOutputStream(aSessionSoket
  37. .getOutputStream());
  38. list.add(aDataOutput);
  39. while (true) {
  40. String msg = aDataInput.readUTF(); // read msg.
  41. if (!msg.equals("connect...")) {
  42. System.out.println("ip: "
  43. + aSessionSoket.getInetAddress());// ip.
  44. System.out.println("receive msg: " + msg);
  45. for (int i = 0; i < list.size(); i++) {
  46. DataOutputStream output = (DataOutputStream) list
  47. .get(i);
  48. output.writeUTF(msg + "----" + list.size());
  49. }
  50. if (msg.equals("end"))
  51. break;
  52. }
  53. aDataOutput.writeUTF("");
  54. }
  55. } catch (IOException e) {
  56. // TODO Auto-generated catch block
  57. e.printStackTrace();
  58. } finally {
  59. try {
  60. aDataInput.close();
  61. if (aDataOutput != null)
  62. aDataOutput.close();
  63. list.remove(aDataOutput);
  64. aSessionSoket.close();
  65. } catch (Exception e2) {
  66. e2.printStackTrace();
  67. }
  68. }
  69. }
  70. }
  71. }

附注:以上只是对Android的Socket编程的大致思路和过程,其中缺少了对于InputStream/OututStream 的异常处理,连接超时等处理。
本文参考:http://duguyidao.iteye.com/blog/1069736

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注