android客户端利用sokcet通信和向Java服务端发请求,Java服务端把文件发给android客户端调试时需要将 android端 连接的 ip地址 改为您服务器的ip地址 即可服务端截图: android端截图
android端源码如下:
package com.yqq.SocketClient;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.view.View;import android.widget.Toast;public class SocketClient extends Activity {private Socket socket;InputStream inputStream;OutputStream outputStream;Handler mHandler=new Handler(){public void handleMessage(Message msg) {if(msg.what==0x123){Toast.makeText(SocketClient.this,"文件下载完毕", 0).show();}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(com.example.socketclient.R.layout.main);}public void downFile(View v){new Thread(new Runnable() {@Overridepublic void run() {try {socket=new Socket(InetAddress.getByName("172.20.113.1"), 20000);inputStream=socket.getInputStream();outputStream=socket.getOutputStream();outputStream.write("askForFile".getBytes());outputStream.flush();//socket.shutdownOutput();Thread.sleep(3000);byte[] buffer=new byte[1024];File file=new File(getCacheDir(),"测试");FileOutputStream fileOutputStream=new FileOutputStream(file);while(inputStream.read(buffer)!=-1){fileOutputStream.write(buffer);}Looper.prepare();Message message=Message.obtain();message.what=0x123;mHandler.sendMessage(message);Looper.loop();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();}}
评论