zoukankan      html  css  js  c++  java
  • Android Socket编程

    花了大概两天的时间,终于把Android的Socket编程给整明白了。抽空和大家分享一下: 
    Socket Programming on Android 
    Socket 编程基础知识: 
    主要分服务器端编程和客户端编程。 
    服务器端编程步骤: 
    1: 创建服务器端套接字并绑定到一个端口上(0-1023是系统预留的,最好大约1024) 
    2: 套接字设置监听模式等待连接请求 
    3: 接受连接请求后进行通信 
    4: 返回,等待赢一个连接请求 

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

    Android Socket 通信原理注意: 
    1: 中间的管道连接是通过InputStream/OutputStream流实现的。 
    2: 一旦管道建立起来可进行通信 
    3: 关闭管道的同时意味着关闭Socket 
    4: 当对同一个Socket创建重复管道时会异常 
    5: 通信过程中顺序很重要:服务器端首先得到输入流,然后将输入流信息输出到其各个客户端 
        客户端先建立连接后先写入输出流,然后再获得输入流。不然活有EOFException的异常。 

    下面是关于在服务器端编程的代码:

    Java代码  收藏代码
    1. import java.io.DataInputStream;  
    2. import java.io.DataOutputStream;  
    3. import java.io.IOException;  
    4. import java.net.ServerSocket;  
    5. import java.net.Socket;  
    6. import java.util.ArrayList;  
    7.   
    8. /** 
    9.  *@author Andrew.Lee 
    10.  *@create 2011-6-1 下午04:45:19 
    11.  *@version 1.0 
    12.  *@see 
    13.  */  
    14. public class Server {  
    15.     static ServerSocket aServerSocket = null; // Server Socet.  
    16.     DataInputStream aDataInput = null; // Server input Stream that to  
    17.     // receive msg from client.  
    18.     DataOutputStream aDataOutput = null; // Server output Stream that to  
    19.     static ArrayList list = new ArrayList();  
    20.   
    21.     public static void main(String[] args) {  
    22.         try {  
    23.             aServerSocket = new ServerSocket(50003); // listen 8888 port.  
    24.             System.out.println("already listen 50003 port.");  
    25.         } catch (Exception e) {  
    26.             e.printStackTrace();  
    27.         }  
    28.         int num = 0;  
    29.         while (num < 10) {  
    30.             Socket aSessionSoket = null;  
    31.             try {  
    32.                 aSessionSoket = aServerSocket.accept();  
    33.                 MyThread thread = new Server().new MyThread(aSessionSoket);  
    34.                 thread.start();  
    35.                 num = list.size();  
    36.             } catch (IOException e1) {  
    37.                 // TODO Auto-generated catch block  
    38.                 e1.printStackTrace();  
    39.             }  
    40.         }  
    41.     }  
    42.   
    43.     class MyThread extends Thread {  
    44.         Socket aSessionSoket = null;  
    45.   
    46.         public MyThread(Socket socket) {  
    47.             aSessionSoket = socket;  
    48.         }  
    49.   
    50.         public void run() {  
    51.             try {  
    52.                 aDataInput = new DataInputStream(aSessionSoket.getInputStream());  
    53.                 aDataOutput = new DataOutputStream(aSessionSoket  
    54.                         .getOutputStream());  
    55.                 list.add(aDataOutput);  
    56.                 while (true) {  
    57.                     String msg = aDataInput.readUTF(); // read msg.  
    58.                     if (!msg.equals("connect...")) {  
    59.                         System.out.println("ip: "  
    60.                                 + aSessionSoket.getInetAddress());// ip.  
    61.                         System.out.println("receive msg: " + msg);  
    62.                         for (int i = 0; i < list.size(); i++) {  
    63.                             DataOutputStream output = (DataOutputStream) list  
    64.                                     .get(i);  
    65.                             output.writeUTF(msg + "----" + list.size());  
    66.                         }  
    67.                         if (msg.equals("end"))  
    68.                             break;  
    69.                     }  
    70.                     aDataOutput.writeUTF("");  
    71.                 }  
    72.   
    73.             } catch (IOException e) {  
    74.                 // TODO Auto-generated catch block  
    75.                 e.printStackTrace();  
    76.             } finally {  
    77.                 try {  
    78.                     aDataInput.close();  
    79.                     if (aDataOutput != null)  
    80.                         aDataOutput.close();  
    81.                     list.remove(aDataOutput);  
    82.                     aSessionSoket.close();  
    83.   
    84.                 } catch (Exception e2) {  
    85.                     e2.printStackTrace();  
    86.                 }  
    87.   
    88.             }  
    89.   
    90.         }  
    91.     }  
    92. }  


    注意问题:为了实现对于多个客户端的处理,使用了多线程的操作,每个线程维护一个Socket的连接与通信,新连接的Socket的管道被加入到ArrayList中。对于输出流的操作是对于所有的连接的客户端进行写数据。对于关闭了Socket的客户端管道从List中移除。 
    客户端编程代码:

    Java代码  收藏代码
    1. package com.daisy.android.network;  
    2.   
    3. import java.io.DataInputStream;  
    4. import java.io.DataOutputStream;  
    5. import java.io.IOException;  
    6. import java.net.InetSocketAddress;  
    7. import java.net.Socket;  
    8. import java.net.SocketAddress;  
    9. import java.net.UnknownHostException;  
    10.   
    11. import android.app.Activity;  
    12. import android.os.Bundle;  
    13. import android.os.Handler;  
    14. import android.os.Message;  
    15. import android.util.Log;  
    16. import android.view.View;  
    17. import android.view.View.OnClickListener;  
    18. import android.widget.Button;  
    19. import android.widget.EditText;  
    20. import android.widget.TextView;  
    21.   
    22. /** 
    23.  *@author Andrew.Lee 
    24.  *@create 2011-5-28 下午02:26:20 
    25.  *@version 1.0 
    26.  *@see 
    27.  */  
    28.   
    29. public class SocketActivity extends Activity {  
    30.     EditText editText = null;  
    31.     Button sendButton = null;  
    32.     TextView display = null;  
    33.     Socket client = null;  
    34.     MyHandler myHandler;  
    35.     DataOutputStream dout;  
    36.     DataInputStream din;  
    37.   
    38.     public void onCreate(Bundle savedInstanceState) {  
    39.         super.onCreate(savedInstanceState);  
    40.         setContentView(R.layout.clientsocket);  
    41.         editText = (EditText) findViewById(R.id.message);  
    42.         sendButton = (Button) findViewById(R.id.send);  
    43.         display = (TextView) findViewById(R.id.display);  
    44.         sendButton.setOnClickListener(listener);  
    45.         try {  
    46.             client = new Socket("192.168.0.120", 50003);  
    47.             dout = new DataOutputStream(client.getOutputStream());  
    48.             din = new DataInputStream(client.getInputStream());  
    49.         } catch (UnknownHostException e) {  
    50.             // TODO Auto-generated catch block  
    51.             e.printStackTrace();  
    52.         } catch (IOException e) {  
    53.             // TODO Auto-generated catch block  
    54.             e.printStackTrace();  
    55.         }  
    56.   
    57.         myHandler = new MyHandler();  
    58.   
    59.         MyThread m = new MyThread();  
    60.         m.start();  
    61.     }  
    62.   
    63.     class MyHandler extends Handler {  
    64.         public MyHandler() {  
    65.         }  
    66.   
    67.         // 子类必须重写此方法,接受数据  
    68.         @Override  
    69.         public void handleMessage(Message msg) {  
    70.             // TODO Auto-generated method stub  
    71.             Log.d("MyHandler", "handleMessage......");  
    72.             super.handleMessage(msg);  
    73.             // 此处可以更新UI  
    74.   
    75.             if (client != null && client.isConnected()) {  
    76.                 Log.i("handler..", "*-----*");  
    77.                 try {  
    78.                     dout.writeUTF("connect...");  
    79.                     String message = din.readUTF();  
    80.                     if (!message.equals(""))  
    81.                         display.setText(display.getText().toString() + " "  
    82.                                 + "服务器发来的消息--:" + message);  
    83.                 } catch (IOException e) {  
    84.                     // TODO Auto-generated catch block  
    85.                     e.printStackTrace();  
    86.                 }  
    87.             }  
    88.   
    89.         }  
    90.     }  
    91.   
    92.     class MyThread extends Thread {  
    93.         public void run() {  
    94.             while (true) {  
    95.                 try {  
    96.                     Thread.sleep(1000);  
    97.                 } catch (InterruptedException e) {  
    98.                     // TODO Auto-generated catch block  
    99.                     e.printStackTrace();  
    100.                 }  
    101.                 Message msg = new Message();  
    102.                 SocketActivity.this.myHandler.sendMessage(msg);  
    103.             }  
    104.         }  
    105.     }  
    106.   
    107.     OnClickListener listener = new OnClickListener() {  
    108.   
    109.         @Override  
    110.         public void onClick(View v) {  
    111.             // TODO Auto-generated method stub  
    112.             String sendText = editText.getText().toString();  
    113.             try {  
    114.                 // din = new DataInputStream(client.getInputStream());  
    115.                 dout.writeUTF(sendText);  
    116.                 /* 
    117.                  * display.setText(display.getText().toString() + " " + 
    118.                  * "服务器发来的消息:" + din.readUTF()); 
    119.                  */  
    120.                 /* 
    121.                  * display.setText(display.getText().toString() + " " + 
    122.                  * "服务器发来的消息--:" + din.readUTF()); 
    123.                  */  
    124.             } catch (UnknownHostException e) {  
    125.                 // TODO Auto-generated catch block  
    126.                 e.printStackTrace();  
    127.             } catch (IOException e) {  
    128.                 // TODO Auto-generated catch block  
    129.                 e.printStackTrace();  
    130.             }  
    131.         }  
    132.     };  
    133. }  


    注意:为实现对于UI的间歇性刷新操作,使用到了Handler的消息机制。 

    附注:以上只是对Android的Socket编程的大致思路和过程,其中缺少了对于InputStream/OututStream 的异常处理,连接超时等处理。 

    摘自:http://duguyidao.iteye.com/blog/1069736

  • 相关阅读:
    python3(四)list tuple
    python3(三)enc
    python3(二)
    Scala学习
    spark本地开发环境搭建及打包配置
    最常见的 Git 问题和操作清单汇总
    Idea离线安装plugins插件 如Lombok
    springboot httpsession.getAtt....is null
    idea打包报错Cleaning up unclosed ZipFile for archive D:m2commons-beanutilscommons-beanutils1.9.2...
    springboot https证书配置
  • 原文地址:https://www.cnblogs.com/antyi/p/3853615.html
Copyright © 2011-2022 走看看