Android PC机的TCP图片传输

本文介绍了一种从PC主机向Android设备传输文件的方法,包括建立连接、接收并保存文件到本地存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package wifi.wifi;

public class CommunicationDeal {
     public static final int dataHeadLength = 10;
     public static final int fileNameLength = 5 ;
     public static final int packetSize     = 4096;
     public static String filename = "text.png";
}
//----------------------------------------------------------------------------

 

package wifi.wifi;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import wifi.wifi.UDPTransferVideo.surfaceView;
import wifi.wifi.UDPTransferVideo.surfaceView.UdpRevThread;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Picture;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

public class TCPService extends Activity{

  DatagramSocket ds ;
     private static int UDP_PORT = 56345;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.image); 
   surfaceView myView = new surfaceView(this);
   setContentView(myView);
  } 
  public class surfaceView extends SurfaceView implements SurfaceHolder.Callback{
         private Paint mPaint ;
         //private Bitmap mBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ic_launcher);
         private Bitmap mBitmap;
   public surfaceView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    mPaint = new Paint();
    this.setFocusable(true);
    this.requestFocus();
    this.getHolder().addCallback(this);
    mPaint.setAntiAlias(true);
    mPaint.setColor(Color.WHITE);
    mPaint.setTextSize(24);
    try {
     ds = new DatagramSocket(UDP_PORT);
    } catch (SocketException e) {
     // TODO Auto-generated catch block
     Toast.makeText(getContext(),"UDP创建失败", Toast.LENGTH_SHORT);
    }
   }
   @Override
   public void surfaceChanged(SurfaceHolder holder, int format, int width,
     int height) {
    // TODO Auto-generated method stub
    
   }
   @Override
   public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    //doDraw();
    connnect("10.10.87.213",6666);
    
   }
   @Override
   public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    
   }
   public void doDraw(){
    byte[] images = new byte[100];
    Canvas canvas = this.getHolder().lockCanvas();
    canvas.drawColor(Color.WHITE);
    canvas.drawBitmap(mBitmap, 0, 0, null);
    this.getHolder().unlockCanvasAndPost(canvas);
   } 
   public Bitmap ChangeArrayToBitmap(byte[] array){
    //ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //mBitmap.compress(CompressFormat.PNG,0, baos);
    //byte[] image = baos.toByteArray();
    System.out.println("Length:"+array.length);
    return BitmapFactory.decodeByteArray(array, 0, array.length) ;
   }
    
      public void connnect(String ip,int port){
       Socket s = null;
    try {
     s = new Socket(ip,port);
     System.out.println("Server!");
     InputStream input = s.getInputStream();
     OutputStream SocketOutput = s.getOutputStream();
     DataOutputStream dos = new DataOutputStream(SocketOutput);
     DataInputStream dis = new DataInputStream(input);
     OutputStream output = null; 
     long fileSize = dis.readLong();
     System.out.println("fileSize:" + fileSize);
        //byte[] DataHead = new byte[CommunicationDeal.dataHeadLength];
        //input.read(DataHead);
        //byte[] fileNameByteArray = new byte[CommunicationDeal.fileNameLength];
        //System.arraycopy(DataHead, 0, fileNameByteArray, 0, CommunicationDeal.fileNameLength);
        //String filename = new String(fileNameByteArray).trim();
     String SDPath =  Environment.getExternalStorageDirectory().toString();
     System.out.println(SDPath);
              File file = new File(SDPath+File.separator+CommunicationDeal.filename);
              System.out.println(file.getPath());
        byte[] buffer = new byte[CommunicationDeal.packetSize];
        //byte[] file = new byte[(int)fileSize];
        try{
        output = new FileOutputStream(file);
        }catch(FileNotFoundException e){
         System.out.println("找不到文件");
        }
  
        System.out.println("fileSize:" + fileSize);
           int readSize = 0 ;
           int length   = 0 ;
          
           while(-1 != (readSize=dis.read(buffer,0,CommunicationDeal.packetSize))){
            
            output.write(buffer , 0 , readSize);
            output.flush();
            length += readSize ;        
            System.out.println("length:"+length);
           }
     input.close();
     output.close();
     dis.close();
     s.close();
        mBitmap = BitmapFactory.decodeFile(file.getPath());
     //mBitmap = BitmapFactory.decodeByteArray(file, 0, file.length);
     doDraw();
    } catch (UnknownHostException e) {
     e.printStackTrace();
     System.out.println("异常");
    } catch (IOException e) {
     e.printStackTrace();
     System.out.println("读入异常");
    }finally{
     if(s!=null){
      try {
       s.close();
       s = null;
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    }
   }
  }
 }

//--------------------------------------------------------------------------------------------------

pc机上的程序,图片由pc机传到android

 

package TCP.test;

import java.awt.Button;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Label;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.net.*;
import java.io.*;

public class Service extends Frame{
    public static  int TCP_PORT = 6666;
    public static  int UDP_PORT = 8888;
    private static int tankID = 100 ;
    static String serverIP = "10.10.87.213";
    private String Client  = null;
    private int Client_udpPort = 0;
    List<Client>clients = new ArrayList<Client>();
   
    //--------------------------------------------------------------------------------------------------------------------------------------------------
    TextField IP = new TextField("10.10.87.213",12);
    TextField TCPPORT = new TextField(Integer.toString(Service.TCP_PORT),6);
    TextField UDPPORT = new TextField(Integer.toString(Service.UDP_PORT),6);
    TextField Infor   = new TextField("请输入IP端口号启动服务器",24);
    Button ok = new Button("确定");
    static Service tws = null;
   
    private static Toolkit tk = Toolkit.getDefaultToolkit();
    Image ball = tk.getImage(Service.class.getClassLoader().getResource("Inages/ball.png"));
 public Service() { 
  // TODO Auto-generated constructor stub
  this.setLayout(new FlowLayout());
  this.setLocation(300, 300);
  this.add(new Label("服务器地址:"));
  this.add(IP);
  this.add(new Label("服务器TCP端口:"));
  this.add(TCPPORT);
  this.add(new Label("服务器UDP端口:"));
  this.add(UDPPORT);
  this.setVisible(true); 
  this.add(ok);
  this.add(Infor);
  this.pack();
        this.setResizable(false);
  ok.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    Service.serverIP = IP.getText();
    Service.TCP_PORT = Integer.parseInt(TCPPORT.getText());
    Service.UDP_PORT = Integer.parseInt(UDPPORT.getText());
    setVisible(true);
    Infor.setText("服务器器运行中");
    repaint();
    tws.start();  
   }
   
  });
  
  this.addWindowListener(new WindowAdapter(){

   @Override
   public void windowClosing(WindowEvent arg0) {
    // TODO Auto-generated method stub
    setVisible(false);  
             System.exit(0);
      }
   
  });
 }
 public void displayInfo(String info){
      Infor.setText(info);
   this.repaint();
   }
 //----------------------------------------------------------------------------------------
    public void start(){
     try {    
   ServerSocket ss = new ServerSocket(TCP_PORT);
   System.out.println("I am here");

   //ss.setSoTimeout(5000);
   while(true){
    Socket s = ss.accept();  
    OutputStream output = s.getOutputStream();
    InputStream  socketInput = s.getInputStream();
    DataOutputStream dos = new DataOutputStream(output);
    DataInputStream dis = new DataInputStream(socketInput);
    String IP = s.getInetAddress().getHostAddress();
    System.out.println("IP:"+IP); 
             File file = new File("src/Inages/ball.png");
                InputStream Input = new FileInputStream(file);
       byte[] buffer = new byte[4096];
    int readSize = 0;
    int length   = 0;
    dos.writeLong(file.length());
    System.out.println("fileSize:"+(int)file.length());
    while(-1 != (readSize = Input.read(buffer))){
     dos.write(buffer, 0, readSize);
     dos.flush();
         length += readSize;
         System.out.println(length);
    }
    output.close();
    Input.close();
    dis.close();
    dos.close();
       s.close();
    System.out.println("Client Connect :" + s.getInetAddress() + "Port:" + s.getPort() + "UDP Port" + Client_udpPort);
   }
  } catch (IOException e) {
   e.printStackTrace();
   displayInfo(Integer.toString(TCP_PORT)+ "已被别的程序占用");
  }
    }
 public static void main(String[] args) {
  tws = new Service();
 }
    public class Client{
     String IP ;
     int UDP_PORT ;
     Client(String ip ,int port){
      this.IP = ip;
      this.UDP_PORT = port ;
     }
    }
   
    public byte[] ChangeImageToArray(Image images){
     //File image = new File("D:/workspace/android/src/Inages/ball.png");   
     try {
   File image = new File(Service.class.getClassLoader().getResource("Inages/ball.png").toURI());  
   InputStream is = new FileInputStream(image);
   DataInputStream dis = new DataInputStream(is);
   byte[] b = new byte[(int) image.length()];
   dis.read(b);
   dis.close();
   System.out.println("数组长度:"+b.length);
   return b;
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   System.out.println("找不到文件");
  } catch (Exception e){
   System.out.println("读取文件失败");
  }
     return null;
    }
   
    public class udpThread implements Runnable{
     DatagramSocket ds = null;
     byte[] b  ;
     byte[] a = new byte[1024] ;
  int dataCount = 0;
  int length=0;
  
  ByteArrayInputStream bais;
  DataOutputStream dos ;
  ByteArrayOutputStream baos;
  public void run() {
   try {
    ds = new DatagramSocket(UDP_PORT);
    b=ChangeImageToArray(null);
       bais = new ByteArrayInputStream(b);
    //DataInputStream dis = new DataInputStream(bais);
    baos = new ByteArrayOutputStream();
    dos = new DataOutputStream(baos);
   } catch (SocketException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }         
   while(true){
     try {         
      if((length=bais.read(a,0,1024)) != -1) {
       dos.write(a, 0, length);
       dataCount++;
       ds.send(new DatagramPacket(baos.toByteArray(), baos.toByteArray().length, new InetSocketAddress(Client, Client_udpPort)));
      }
      else break ;
      System.out.println("dataCount"+dataCount);      
     } catch (Exception e) {
      e.printStackTrace();
     }
   }
  }    
    }
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值