基于socket的图片传输demo( Python 和android app)

最近项目中需要做类似信息推送的功能,这里用Python和Android app socket来实现。

一、功能分析

信息推送,并直接展示。一图片为例,客户端发送一个图片到服务端,并在服务端显示图片,大小根据服务端界面设置

二、模块划分

客户端  python实现

服务器端 Android实现

三、上代码

服务端

Activity + 布局+ manifest 三个文件

Activity中主要是逻辑实现

  1 package com.example.tcpimagereceiveactivity;
  2 
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.DataInputStream;
  5 import java.net.ServerSocket;
  6 import java.net.Socket;
  7 import java.util.ArrayList;
  8 import java.util.List;
  9 
 10 import android.app.Activity;
 11 import android.graphics.Bitmap;
 12 import android.graphics.Bitmap.CompressFormat;
 13 import android.graphics.BitmapFactory;
 14 import android.os.Bundle;
 15 import android.os.Handler;
 16 import android.widget.ImageView;
 17 
 18 public class MainActivity extends Activity
 19 {
 20 
 21     Bitmap bmp;
 22 
 23     @Override
 24     protected void onCreate(Bundle savedInstanceState)
 25     {
 26         super.onCreate(savedInstanceState);
 27         setContentView(R.layout.activity_server);
 28 
 29         new Thread(runnable).start();
 30     }
 31 
 32     private void startListen()
 33     {
 34         try
 35         {
 36             final ServerSocket server = new ServerSocket(33456);
 37             Thread th = new Thread(new Runnable()
 38             {
 39                 public void run()
 40                 {
 41                     while (true)
 42                     {
 43                         try
 44                         {
 45                             Socket socket = server.accept();
 46 
 47                             receiveFile(socket);
 48                         } catch (Exception e)
 49                         {
 50                         }
 51                     }
 52                 }
 53 
 54             });
 55 
 56             th.run(); // 启动线程运行
 57         } catch (Exception e)
 58         {
 59             e.printStackTrace();
 60         }
 61     }
 62 
 63     Runnable runnable = new Runnable()
 64     {
 65         @Override
 66         public void run()
 67         {
 68 
 69             startListen();
 70         }
 71     };
 72 
 73     private Handler myHandler = new Handler()
 74     {
 75         public void handleMessage(android.os.Message msg)
 76         {
 77 
 78             super.handleMessage(msg);
 79 
 80             ImageView view = (ImageView) findViewById(R.id.imageView1);
 81             view.setImageBitmap(bmp);
 82 
 83         };
 84     };
 85 
 86     public void receiveFile(Socket socket)
 87     {
 88         int length = 0;
 89         DataInputStream dis = null;
 90         try
 91         {
 92             try
 93             {
 94                 List<Byte> list = new ArrayList<Byte>();
 95 
 96                 dis = new DataInputStream(socket.getInputStream());
 97 
 98                 byte[] inputByte = new byte[1024];
 99                 System.out.println("开始接收数据...");
100                 while ((length = dis.read(inputByte, 0, inputByte.length)) > 0)
101                 {
102                     // 重要:把length作为参数传进去,
103                     // 由于网络原因,DataInputStream.read并不是每次都返回byteCount个字节,有可能比byteCount小,
104                     // 那么inputByte[]后面的字节填充的是无效数据,要把它忽略掉.否则。图片拿过来有马赛克
105                     appendByteArrayIntoByteList(list, inputByte, length);
106                 }
107 
108                 Byte[] IMG = (Byte[]) list.toArray(new Byte[0]);
109 
110                 byte[] img = new byte[IMG.length];
111                 for (int i = 0; i < IMG.length; i++)
112                 {
113                     img[i] = IMG[i];
114                 }
115                 
116 
117                 ByteArrayOutputStream outPut = new ByteArrayOutputStream();
118                 bmp = BitmapFactory.decodeByteArray(img, 0, img.length);
119                 bmp.compress(CompressFormat.PNG, 100, outPut);
120 
121                 myHandler.obtainMessage().sendToTarget();
122 
123                 
124             } catch (Exception e)
125             {
126                 e.printStackTrace();
127             } finally
128             {
129 
130                 if (dis != null)
131                     dis.close();
132                 if (socket != null)
133                     socket.close();
134             }
135         } catch (Exception e)
136         {
137 
138         }
139 
140     }
141 
142     private void appendByteArrayIntoByteList(List<Byte> list, byte[] array)
143     {
144         final int length = array.length;
145         for (int ii = 0; ii < length; ++ii)
146         {
147             list.add(array[ii]);
148         }
149         return;
150     }
151     
152     private void appendByteArrayIntoByteList(List<Byte> list, byte[] array, int count)
153     {
154         for (int ii = 0; ii < count; ++ii)
155         {
156             list.add(array[ii]);
157         }
158         return;
159     }
160 
161 }
View Code

 

布局文件中主要是界面

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context=".TCPServerTestActivity" >
10 
11 
12     <TextView
13         android:id="@+id/textView1"
14         android:layout_width="wrap_content"
15         android:layout_height="wrap_content"
16         android:text="@string/hello_world" />
17 
18 
19     <ImageView
20         android:id="@+id/imageView1"
21         android:layout_width="wrap_content"
22         android:layout_height="wrap_content"
23         android:layout_alignRight="@+id/textView1"
24         android:layout_below="@+id/textView1"
25         android:layout_marginRight="32dp"
26         android:layout_marginTop="50dp"
27         android:src="@drawable/ic_launcher" />
28 
29 
30 </RelativeLayout>
View Code

 

manifest文件中添加网络权限

1 <uses-permission android:name="android.permission.INTERNET" />

 

客户端

导入包 socket sys

import socket
import sys


s = socket.socket()

s.connect(("192.168.1.101",33456))
f=open ("1.jpg", "rb") 
l = f.read(1024)
while (l):
    s.send(l)
    l = f.read(1024)
s.close()
View Code

 

四、测试

步骤先启动 服务端(在实体机中),在运行客户端。

引用自

五、扩展功能

传某种格式的文字

传动态图

传影音视频

尽请关注

posted @ 2015-01-25 19:43  Geek0007  阅读(2281)  评论(0)    收藏  举报