Android网络编程Socket

移动开发 Android
Socket通常也称做”套接字“,用于描述IP地址和端口,它就是网络通信过程中端点的抽象表示。值得一提的是,Java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用起来很方便!

在Android的网络通讯中,通常会使用Socket进行设备间数的数据通讯,使用Http来对网络数据进行请求。
1、Socket(套接字)
不管是有过Java开发经验还是.NET开发经验的同学都应该对Socket有或多或少的了解,常见的TCP或者UDP协议其实都是基于Socket来实现的。
Socket是用于描述网络上的一个设备中的一个进程或者应用程序的,Socket由IP地址和端口号两部分组成。IP地址用来定位设备,端口号用来定位 应用程序或者进程,比如我们常见的运行在80端口上的HTTP协议。Socket的常见格式为:192.168.1.1:1234。
那么应用程序是如何通过Socket来与网络中的其他设备进行通讯的呢?通常情况下,Socket通信有两部分,一部分为监听的Server端,一部分为 主动请求连接的Client端。Server端会一直监听Socket中的端口直到有请求为止,当Client端对该端口进行连接请求时,Server端 就给予应答并返回一个Socket对象,以后在Server端与Client端的数据交换就可以使用这个Socket来进行操作了。
2、Android中使用Socket进行数据交换
ServerSocket
建立服务端(Server)时,需要使用ServerSocket对象,这个对象会自动对其构造函数中传入的端口号进行监听,并在收到连接请求后,使 用ServerSocket.accept()方法返回一个连接的的Socket对象。这个方法并不需要我们像在.NET中那样使用Start方法,它会 自动进行监听的。
Socket
不管建立客户端(Client)还是在进行其他数据交换方面的操作时,都需要使用Socket类。Socket类在进行初始化时需要出入Server 端的IP地址和端口号,并返回连接到Server端的一个Socket对象,如果是连接失败,那么将返回异常。同ServerSocket,也是自动进行 连接请求的。
通过上面两个步骤后,Server端和Client端就可以连接起来了,但是仅仅连接起来是没有任何作用的,数据交换才是我们的目的,这时候就需要用到IO流中的OutputStream类和InputStream类。
OutputStream——可写流
当应用程序需要对流进行数据写操作时,可以使用Socket.getOutputStream()方法返回的数据流进行操作。
InputStream——可读流
当应用程序要从流中取出数据时,可以使用Socket.getInputStream()方法返回的数据流进行操作。
看看完整的代码吧

  1. View Code  
  2.  package LiB.Demo; 
  3.   
  4.  import java.io.BufferedReader; 
  5.  import java.io.BufferedWriter; 
  6.  import java.io.IOException; 
  7.  import java.io.InputStreamReader; 
  8.  import java.io.OutputStreamWriter; 
  9.  import java.net.ServerSocket; 
  10.  import java.net.Socket; 
  11.   
  12.  public class SocketHelper { 
  13.      private static ServerSocket serverSocket = null
  14.      private static Socket client = null
  15.      private final static int port = 9048
  16.      private static BufferedReader br= null;  
  17.      private static BufferedWriter bw = null
  18.       
  19.      /** 
  20.       * 创建一个SocketServer对象用来建立服务器 
  21.       * @throws IOException 
  22.  */ 
  23.      public static void CreateServer() throws IOException 
  24.      { 
  25.          serverSocket = new ServerSocket(port,10); 
  26.          System.out.println("start listening..."); 
  27.      } 
  28.      /** 
  29.       * 创建一个Socket对象用来连接SocketServer对象 
  30.       * @param dstName Server对象的ip地址 
  31.       * @return  
  32.       * @throws IOException 
  33.  */ 
  34.      public static Socket CreateClient(String dstName) throws IOException 
  35.      { 
  36.          Socket socket = new Socket(dstName, port); 
  37.          //Socket sockets = new Socket("192.168.8.12",port); 
  38.          return socket; 
  39.      } 
  40.      /** 
  41.       * 返回一个已经连接到服务器上的Socket对象 
  42.       * @throws IOException 
  43.  */ 
  44.      public static void GetClinetSocket() throws IOException 
  45.      { 
  46.          client = serverSocket.accept(); 
  47.          System.out.println("get a connected client"); 
  48.      } 
  49.      /** 
  50.       * 向socket对象所获取的流中发送数据 
  51.       * @param socket 
  52.       * @param msg 
  53.       * @throws IOException 
  54.  */ 
  55.      public static void SendMsg(Socket socket , String msg) throws IOException 
  56.      { 
  57.          bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 
  58.          bw.write(msg); 
  59.          bw.flush(); 
  60.          bw.close(); 
  61.      } 
  62.       
  63.      /** 
  64.       * 获取socket对象流中数据 
  65.       * @param socket 
  66.       * @param msg 
  67.       * @return 
  68.       * @throws IOException 
  69.  */ 
  70.      public static String ReceiveMsg(Socket socket, String msg) throws IOException 
  71.      { 
  72.          br = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
  73.          String receiveMsg = "Receive msg:"+ br.readLine(); 
  74.          br.close(); 
  75.          return receiveMsg; 
  76.      } 
  77.       
  78.      /** 
  79.       * 释放socket对象 
  80.       * @throws IOException 
  81.  */ 
  82.      public static void Close() throws IOException 
  83.      { 
  84.          if(client != null
  85.          { 
  86.              client.close(); 
  87.          } 
  88.          if(serverSocket != null
  89.          { 
  90.              serverSocket.close(); 
  91.          } 
  92.      } 
  93.  } 

下页将为您介绍HTTP通讯的内容

#p#

3、HTTP通讯
在开始前先简单介绍下HTTP协议中的两种不同的请求方式——GET和POST。GET方式在进行数据请求时,会把数据附加到URL后面传递给服务 器,比如常见的:http://XXX.XXX.XXX/XX.aspx?id=1,POST方式则是将请求的数据放到HTTP请求头中,作为请求头的一 部分传入服务器。所以,在进行HTTP编程前,首先要明确究竟使用的哪种方式进行数据请求的。
在Android中,可以有两种方式可以用来进行Http编程:1、HttpURLConnection;2、HttpClient。
HttpURLConnection
HttpURLConnection是继承自URLConnection的一个抽象类,在HTTP编程时,来自HttpURLConnection的类是所有操作的基础,获取该对象的代码如下:

  1. View Code  
  2.      public HttpURLConnection urlconn= null
  3.      private void Init() throws IOException 
  4.      { 
  5.          if (urlStr==""
  6.          { 
  7.              urlStr="http://www.baidu.com"
  8.          } 
  9.          URL url = new URL(urlStr); 
  10.          //打开一个URL所指向的Connection对象 
  11.          urlconn = (HttpURLConnection)url.openConnection(); 
  12.      }View Code  
  13.      public HttpURLConnection urlconn= null
  14.      private void Init() throws IOException 
  15.      { 
  16.          if (urlStr==""
  17.          { 
  18.              urlStr="http://www.baidu.com"
  19.          } 
  20.          URL url = new URL(urlStr); 
  21.          //打开一个URL所指向的Connection对象 
  22.          urlconn = (HttpURLConnection)url.openConnection(); 
  23.      } 

HttpURLConnection对网络资源的请求在默认情况下是使用GET方式的,所以当使用GET方式时,不需要我们做太多的工作:

  1. View Code  
  2.      public HttpURLConnection urlconn= null
  3.      private void Init() throws IOException 
  4.      { 
  5.          if (urlStr==""
  6.          { 
  7.              urlStr="http://www.baidu.com"
  8.          } 
  9.          URL url = new URL(urlStr); 
  10.          //打开一个URL所指向的Connection对象 
  11.          urlconn = (HttpURLConnection)url.openConnection(); 
  12.      } 
  13.      /** 
  14.       * Http中的get请求,在Url中带有请求的参数,请求的URL格式通常为:"http://XXX.XXXX.com/xx.aspx?param=value" 
  15.       * 在android中默认的http请求为get方式 
  16.       * @return 
  17.       * @throws IOException 
  18.  */ 
  19.      public String HttpGetMethod() throws IOException 
  20.      { 
  21.          if(urlconn == null
  22.          { 
  23.              Init(); 
  24.          } 
  25.          String result = StreamDeal(urlconn.getInputStream()); 
  26.          urlconn.disconnect(); 
  27.          return result; 
  28.      } 

当我们需要使用POST方式时,就需要使用setRequestMethod()来设置请求方式了。

  1. View Code  
  2.      /** 
  3.       * Http中的post请求,不在Url中附加任何参数,这些参数都会通过cookie或者session等其他方式以键值对的形式key=value传送到服务器上,完成一次请求 
  4.       * 请求的URL格式通常为:"http://XXX.XXXX.com/xx.aspx" 
  5.       * @param param 请求的键名 
  6.       * @param value 请求的数据值 
  7.       * @throws IOException 
  8.  */ 
  9.      public String HttpPostMethod(String key,String value) throws IOException 
  10.      { 
  11.          if (urlconn==null
  12.          { 
  13.              Init(); 
  14.          } 
  15.          //设置该URLConnection可读 
  16.          urlconn.setDoInput(true); 
  17.          //设置该URLConnection可写 
  18.          urlconn.setDoOutput(true); 
  19.          //使用POST方式来提交数据 
  20.          urlconn.setRequestMethod("POST"); 
  21.          //不运行缓存 
  22.          urlconn.setUseCaches(false); 
  23.          //当使用POST方式进行数据请求时,我们可以手动执行connect动作,当然,这个动作其实在getOutputStream()方法中会默认执行的 
  24.  //上面那些设置URLConnection属性的动作,一定要在connect动作执行前,因为一旦动作已经执行,熟悉设置就没有任何作用了 
  25.          urlconn.connect(); 
  26.          //使用POST方式时,我们需要自己构造部分Http请求的内容,因此我们需要使用OutputStream来进行数据写如操作 
  27.          OutputStreamWriter writer = new OutputStreamWriter(urlconn.getOutputStream()); 
  28.           
  29.          String urlQueryStr = key+"="+URLEncoder.encode(value, "Utf-8"); 
  30.          writer.write(urlQueryStr); 
  31.           
  32.          writer.flush(); 
  33.          writer.close(); 
  34.          //获取返回的内容 
  35.          String result = StreamDeal(urlconn.getInputStream()); 
  36.          return result; 
  37.           
  38.      } 

HttpClient
这个类并不是来自Android的,而是来自org.apache.http。和HttpURLConnection相同,HttpClient也存在GET和POST两种方式。

HttpGet
在HttpClient中,我们可以非常轻松使用HttpGet对象来通过GET方式进行数据请求操作,当获得HttpGet对象后我们可以 使用HttpClient的execute方法来向我们的服务器发送请求。在发送的GET请求被服务器相应后,会返回一个HttpResponse响应对 象,利用这个响应的对象我们能够获得响应回来的状态码,如:200、400、401等等。

  1. View Code  
  2.      public String HttpGetMethod() 
  3.      { 
  4.          String result = ""
  5.          try 
  6.          { 
  7.          HttpGet httpRequest = new HttpGet(urlStr); 
  8.          HttpClient httpClient = new DefaultHttpClient(); 
  9.          HttpResponse httpResponse = httpClient.execute(httpRequest); 
  10.          if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK) 
  11.          { 
  12.              result = EntityUtils.toString(httpResponse.getEntity()); 
  13.          } 
  14.          else 
  15.          { 
  16.              result = "null"
  17.          } 
  18.          return result; 
  19.          } 
  20.          catch(Exception e) 
  21.          { 
  22.              return null
  23.          } 
  24.      } 

 HttpPost
     当我们使用POST方式时,我们可以使用HttpPost类来进行操作。当获取了HttpPost对象后,我们就需要向这个请求体传入键值 对,这个键值对我们可以使用NameValuePair对象来进行构造,然后再使用HttpRequest对象最终构造我们的请求体,***使用 HttpClient的execute方法来发送我们的请求,并在得到响应后返回一个HttpResponse对象。其他操作和我们在HttpGet对象 中的操作一样。

  1. View Code  
  2.  public String HttpPostMethod(String key,String value) 
  3.      { 
  4.          String result = ""
  5.          try 
  6.          { 
  7.          // HttpPost连接对象 
  8.          HttpPost httpRequest = new HttpPost(urlStr); 
  9.          // 使用NameValuePair来保存要传递的Post参数 
  10.          List<NameValuePair> params = new ArrayList<NameValuePair>(); 
  11.          // 添加要传递的参数 
  12.          params.add(new BasicNameValuePair(key, value)); 
  13.          // 设置字符集 
  14.          HttpEntity httpentity = new UrlEncodedFormEntity(params, "Utf-8"); 
  15.          // 请求httpRequest 
  16.          httpRequest.setEntity(httpentity); 
  17.          // 取得默认的HttpClient 
  18.          HttpClient httpclient = new DefaultHttpClient(); 
  19.          // 取得HttpResponse 
  20.          HttpResponse httpResponse = httpclient.execute(httpRequest); 
  21.          // HttpStatus.SC_OK表示连接成功 
  22.          if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
  23.              // 取得返回的字符串 
  24.              result = EntityUtils.toString(httpResponse.getEntity()); 
  25.              return result;  
  26.          } else { 
  27.               return "null"
  28.          } 
  29.          } 
  30.          catch(Exception e) 
  31.          { 
  32.              return null
  33.          } 
  34.      } 

 三、总结
可以说Android如果不进行与网络资源进行交互的话,它就和我们当初的普通系统没有任何区别了,所以网络编程对Android开发来说有非常特殊的意义。

责任编辑:闫佳明 来源: my.eoe.cn
相关推荐

2010-03-03 16:19:29

Python Sock

2013-03-26 12:46:23

Android开发So

2015-04-24 09:48:59

TCPsocketsocket编程

2012-03-19 10:55:27

JavaSocket

2019-02-12 15:04:09

2016-11-04 21:37:16

PythonSocket

2012-03-19 11:41:30

JavaSocket

2011-06-13 12:11:06

javasocket

2011-06-13 11:23:33

javasocket

2009-09-07 14:29:47

C# Socket编程C# Socket

2024-04-23 13:36:00

2015-07-27 09:53:13

PHP编程过程

2013-09-22 11:03:20

SocketSocket编程

2011-06-13 16:51:19

Qt Socket

2019-09-18 20:07:06

AndroidTCP协议

2019-02-17 10:05:24

TCPSocket网络编程

2010-03-22 10:42:37

Java Socket

2010-03-17 14:22:40

Java Socket

2009-06-11 10:00:05

Java Socket

2022-10-24 08:01:32

Sockets网络协议
点赞
收藏

51CTO技术栈公众号