---
title: "Socket 网络编程"
author: "MagicMa_007"
date: "2012-07-23T08:29:33Z"
tags: ["Java", "Socket"]
categories: ["编程语言"]
slug: "socket"
draft: false
lastmod: "2012-07-23T08:29:33Z"
id: 1603887
url: "https://magicma-007.iteye.com/blog/1603887"
---

### 基于Socket的网络编程

Android的网络编程部分，基本上和Java的网络编程是一样的，基本上也分成两种，一种是基于Socket的，另外一种是基于Http协议的。

#### 基于Socket的基本用法，跟Java里面的用法一样，简单回顾一下：

一：服务端

1：启动一个服务器端的socket：ServerSocket server = new ServerSocket(1234);

2：开始侦听请求：Socket client = server.accept();

3：取得输入和输出流：

4：然后就可以通过流来进行网络传输了

5：最好要记得关闭流和Server

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

01. ServerSocket server=new ServerSocket(1234);
02. Socket client=server.accept();
03. InputStream in = client.getInputStream();
04. OutputStream out=client.getOutputStream();
05. byte bs\[] = new byte\[1024];
06. in.read(bs);
07. String str= new String(bs);
08. System.out.println(str);
09. out.write("Server send".getBytes());
10. out.flush();
11. client.close();

![](http://sishuok.com/forum/upload/2012/2/27/6610c084cc9e21a1a02b70717ba533bc__1.jpg) 

二：客户端：

1：发起一个socket连接：Socket server = new Socket("192.168.1.2",1234);

2：取得输入和输出流：

3：然后就可以通过流来进行网络传输了

4：最好要记得关闭流和Socket

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

1. String str = "client send";
2. out.write(str.getBytes());
3. out.flush();
4. byte bs\[] = new byte\[1024];
5. in.read(bs);
6. System.out.println(new String(bs));
7. server.close();

当然这样实现很不好，应该包装成上层的流或者Reader、Writer来做。

#### 包装成Reader和Writer的服务端示例：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

1. ServerSocket server=new ServerSocket(1234);
2. Socket client=server.accept();
3. BufferedReader in=
4. new BufferedReader(new InputStreamReader(client.getInputStream()));
5. PrintWriter out=new PrintWriter(client.getOutputStream());
6. String str=in.readLine();
7. System.out.println(str);
8. out.println("Server send");
9. out.flush();

#### 包装成Reader和Writer的客户端示例：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

1. Socket server = new Socket("192.168.0.100", 1234);
2. BufferedReader in = new BufferedReader(new InputStreamReader(
3. server.getInputStream()));
4. PrintWriter out = new PrintWriter(server.getOutputStream());
5. String str = "client send";
6. out.println(str);
7. out.flush();
8. System.out.println(in.readLine());
9. server.close();

### 使用HttpURLConnection

基于Http协议的基本用法，可以使用HttpURLConnection，也可以使用Apache的Http操作包，具体的使用方式下面分别来示例。

#### 要让应用使用网络，需要在Manifest文件中添加权限：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

01. &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
02. HttpURLConnection默认使用get的方式与后台交互
03. HttpURLConnection conn = null;
04. try {
05. URL  u = new URL("http://192.168.0.100:8080/test.jsp?uuid=123");
06. conn = (HttpURLConnection)u.openConnection();
07. BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
08. String line = "";
09. while((line=br.readLine())!=null){
10. Log.i("NetTest","lien="+line);
11. }
12. } catch (Exception e) {e.printStackTrace();}
13. finally{ conn.disconnect();}

#### 请注意一点，在Android3.0以上的版本里面，已经不允许直接在Activity里面进行网络的处理了，建议使用后台线程或者是干脆新建一个线程来运行，比如：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

1. Thread t =new Thread(new Runnable() {
2. public void run() {
3. //上面的代码
4. }
5. });
6. t.start();

#### HttpURLConnection使用Post的方式与后台交互，下载数据部分跟上一个示例是一样的，麻烦在于上传数据到服务器，需要进行设置和处理，如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

1. URL  u = new URL("http://192.168.0.100:8080/test.jsp");
2. conn = (HttpURLConnection)u.openConnection();
3. //因为这个是post请求,下面两个需要设置为true
4. conn.setDoOutput(true);
5. conn.setDoInput(true);

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

01. // 设置以POST方式
02. conn.setRequestMethod("POST");
03. // Post 请求不能使用缓存
04. conn.setUseCaches(false);
05. conn.setInstanceFollowRedirects(true);
06. // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
07. conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
08. //DataOutputStream流
09. DataOutputStream out = new DataOutputStream(conn.getOutputStream());
10. //要上传的参数
11. String content = "uuid=" + URLEncoder.encode("post测试", "utf-8");
12. //将要上传的内容写入流中
13. out.writeBytes(content);
14. //刷新、关闭
15. out.flush();
16. out.close();

#### 使用Apache的Http操作包来实现以Get的方式与后台交互，示例如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

01. //封装用于请求的 方法 对象
02. HttpGet get = new HttpGet("http://192.168.0.100:8080/test.jsp?uuid=uuid121&name=name222");
03. //创建一个Http的客户端对象
04. HttpClient client = new DefaultHttpClient();
05. try{ //发送请求，并获得返回对象
06. HttpResponse response = client.execute(get);
07. //从response对象里面把返回值取出来
08. HttpEntity entity = response.getEntity();
09. //得到返回内容的流，接下来就是流式操作了
10. InputStream in = entity.getContent();
11. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
12. StringBuffer buffer = new StringBuffer();
13. String tempStr = "";
14. while((tempStr=reader.readLine())!=null){
15. buffer.append(tempStr);
16. }
17. in.close();//应该写finally里面去
18. reader.close();//应该写finally里面去
19. Log.i("javass",buffer.toString());
20. }catch(Exception err){err.printStackTrace();}

#### 使用Apache的Http操作包来实现以Post的方式与后台交互，示例如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

01. //封装用于请求的 方法 对象
02. HttpPost post = new HttpPost("http://192.168.0.100:8080/test.jsp");
03. //为post组织参数
04. NameValuePair uuid = new BasicNameValuePair("uuid","postUuid");
05. NameValuePair name = new BasicNameValuePair("name","postname");
06. List&lt;NameValuePair&gt; list = new ArrayList&lt;NameValuePair&gt;();
07. list.add(uuid);
08. list.add(name);
09. //把这些参数封装到HttpEntity中
10. HttpEntity reqEntity = null;
11. reqEntity = new UrlEncodedFormEntity(list);
12. //然后把HttpEntity设置到post对象里面去
13. post.setEntity(reqEntity);
14. //创建一个Http的客户端对象
15. HttpClient client = new DefaultHttpClient();
16. //发送请求，并获得返回对象
17. HttpResponse response = client.execute(post);

后面获取response的Entity等的处理，跟get方式是完全一样的，这里就不去赘述了。

### 操作JSON

在实际应用开发中，网络间传输的数据经常是JSON格式的，除非十分有必要，不会去使用XML。因此必须要掌握Android如何处理JSON数据，Android已经自带了JSON的处理包“org.json”。下面就来看看如何解析已经获取的数据，获取数据的过程就是前面讲的获取的网络返回值。

#### 返回单个对象的情况，示例如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

1. JSONObject j = new JSONObject(jsonData);
2. String uuid = j.getString(“uuid");

#### 返回对象数组的情况，示例如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2751.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2751.html)[打印](http://sishuok.com/forum/blogPost/list/2751.html)

1. JSONArray ja = new JSONArray(jsonData);
2. for(int i=0;i&lt;ja.length();i++){
3. JSONObject j = ja.getJSONObject(i);
4. String retUuid = j.getString("uuid");
5. String retName = j.getString("name");
6. Log.i("javass","ret jsonsss uuid="+retUuid+",name="+retName);
7. }

视频配套PPT，视频地址【 [Android4开发入门经典独家视频课程](http://sishuok.com/product/341)】

原创内容 转自请注明【 [http://sishuok.com/forum/blogPost/list/0/2751.html#7736](http://sishuok.com/forum/blogPost/list/0/2751.html#7736)】