android java服务端_Android/Java从服务器端下载图片
/** * 思想: 1.直接將所有數(shù)據(jù)安裝字節(jié)數(shù)組發(fā)送 2.對(duì)象序列化方式 *//** * thread方式 * * @author Administrator */public class TestSocketActivity4 extends Activity { private static final int FINISH = 0; private Button send = null; private TextView info = null; private Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case FINISH: String result = msg.obj.toString(); // 取出數(shù)據(jù) if ("true".equals(result)) { TestSocketActivity4.this.info.setText("操作成功!"); } else { TestSocketActivity4.this.info.setText("操作失敗!"); } break; } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_test_sokect_activity4); // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() // .detectDiskReads().detectDiskWrites().detectNetwork() // .penaltyLog().build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() // .detectLeakedSqlLiteObjects().detectLeakedClosableObjects() // .penaltyLog().penaltyDeath().build()); this.send = (Button) super.findViewById(R.id.send); this.info = (TextView) super.findViewById(R.id.info); this.send.setOnClickListener(new SendOnClickListener()); } private class SendOnClickListener implements OnClickListener { @Override public void onClick(View v) { try { new Thread(new Runnable() { @Override public void run() { try { //1: Socket client = new Socket("192.168.1.165", 9898); //2: ObjectOutputStream oos = new ObjectOutputStream( client.getOutputStream()); //3: UploadFile myFile = SendOnClickListener.this .getUploadFile(); //4: oos.writeObject(myFile);// 寫文件對(duì)象 // oos.writeObject(null);// 避免EOFException oos.close(); BufferedReader buf = new BufferedReader( new InputStreamReader(client .getInputStream())); // 讀取返回的數(shù)據(jù) String str = buf.readLine(); // 讀取數(shù)據(jù) Message msg = TestSocketActivity4.this.myHandler .obtainMessage(FINISH, str); TestSocketActivity4.this.myHandler.sendMessage(msg); buf.close(); client.close(); } catch (Exception e) { Log.i("UploadFile", e.getMessage()); } } }).start(); } catch (Exception e) { e.printStackTrace(); } } private UploadFile getUploadFile() throws Exception { // 包裝了傳送數(shù)據(jù) UploadFile myFile = new UploadFile(); myFile.setTitle("tangcco安卓之Socket的通信"); // 設(shè)置標(biāo)題 myFile.setMimeType("image/png"); // 圖片的類型 File file = new File(Environment.getExternalStorageDirectory() .toString() + File.separator + "Pictures" + File.separator + "b.png"); InputStream input = null; try { input = new FileInputStream(file); // 從文件中讀取 ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte data[] = new byte[1024]; int len = 0; while ((len = input.read(data)) != -1) { bos.write(data, 0, len); } myFile.setContentData(bos.toByteArray()); myFile.setContentLength(file.length()); myFile.setExt("png"); } catch (Exception e) { throw e; } finally { input.close(); } return myFile; } }}public class UploadFile implements Serializable {private String title;private byte[] contentData;private String mimeType;private long contentLength;private String ext;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public byte[] getContentData() {return contentData;}public void setContentData(byte[] contentData) {this.contentData = contentData;}public String getMimeType() {return mimeType;}public void setMimeType(String mimeType) {this.mimeType = mimeType;}public long getContentLength() {return contentLength;}public void setContentLength(long contentLength) {this.contentLength = contentLength;}public String getExt() {return ext;}public void setExt(String ext) {this.ext = ext;}}下邊是服務(wù)端
public class Main4 {public static void main(String[] args) throws Exception {ServerSocket server = new ServerSocket(9898); // 服務(wù)器端端口System.out.println("服務(wù)啟動(dòng)........................");boolean flag = true; // 定義標(biāo)記,可以一直死循環(huán)while (flag) { // 通過(guò)標(biāo)記判斷循環(huán)new Thread(new ServerThreadUtil(server.accept())).start(); // 啟動(dòng)線程}server.close(); // 關(guān)閉服務(wù)器}}public class ServerThreadUtil implements Runnable {private static final String DIRPATH = "D:" + File.separator + "myfile"+ File.separator; // 目錄路徑private Socket client = null;private UploadFile upload = null;public ServerThreadUtil(Socket client) {this.client = client;System.out.println("新的客戶端連接...");}@Overridepublic void run() {try {ObjectInputStream ois = new ObjectInputStream(client.getInputStream()); // 反序列化this.upload = (UploadFile) ois.readObject(); // 讀取對(duì)象//UploadFile需要和客戶端傳遞過(guò)來(lái)的包名類名相同,如果不同則會(huì)報(bào)異常System.out.println("文件標(biāo)題:" + this.upload.getTitle());System.out.println("文件類型:" + this.upload.getMimeType());System.out.println("文件大小:" + this.upload.getContentLength());PrintStream out = new PrintStream(this.client.getOutputStream());// BufferedWriterout.print(this.saveFile());//返回響應(yīng)//BufferedWriter writer = null;//writer.write("");} catch (Exception e) {e.printStackTrace();} finally {try {this.client.close();} catch (IOException e) {e.printStackTrace();}}}private boolean saveFile() throws Exception { // 負(fù)責(zé)文件內(nèi)容的保存/** * java.util.UUID.randomUUID(): * UUID.randomUUID().toString()是javaJDK提供的一個(gè)自動(dòng)生成主鍵的方法。 UUID(Universally * Unique Identifier)全局唯一標(biāo)識(shí)符,是指在一臺(tái)機(jī)器上生成的數(shù)字,它保證對(duì)在同一時(shí)空中的所有機(jī)器都是唯一的, * 是由一個(gè)十六位的數(shù)字組成 * ,表現(xiàn)出來(lái)的形式。由以下幾部分的組合:當(dāng)前日期和時(shí)間(UUID的第一個(gè)部分與時(shí)間有關(guān),如果你在生成一個(gè)UUID之后, * 過(guò)幾秒又生成一個(gè)UUID, * 則第一個(gè)部分不同,其余相同),時(shí)鐘序列,全局唯一的IEEE機(jī)器識(shí)別號(hào)(如果有網(wǎng)卡,從網(wǎng)卡獲得,沒(méi)有網(wǎng)卡以其他方式獲得 * ),UUID的唯一缺陷在于生成的結(jié)果串會(huì)比較長(zhǎng),字符串長(zhǎng)度為36。 * * UUID.randomUUID().toString()是java JDK提供的一個(gè)自動(dòng)生成主鍵的方法。 UUID(Universally * Unique Identifier)全局唯一標(biāo)識(shí)符, 是指在一臺(tái)機(jī)器上生成的數(shù)字,它保證對(duì)在同一時(shí)空中的所有機(jī)器都是唯一的, * 是由一個(gè)十六位的數(shù)字組成,表現(xiàn)出來(lái)的形式 */File file = new File(DIRPATH + UUID.randomUUID() + "."+ this.upload.getExt());if (!file.getParentFile().exists()) {file.getParentFile().mkdir();}OutputStream output = null;try {output = new FileOutputStream(file);output.write(this.upload.getContentData());return true;} catch (Exception e) {throw e;} finally {output.close();}}}public class UploadFile implements Serializable {private String title;private byte[] contentData;private String mimeType;private long contentLength;private String ext;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public byte[] getContentData() {return contentData;}public void setContentData(byte[] contentData) {this.contentData = contentData;}public String getMimeType() {return mimeType;}public void setMimeType(String mimeType) {this.mimeType = mimeType;}public long getContentLength() {return contentLength;}public void setContentLength(long contentLength) {this.contentLength = contentLength;}public String getExt() {return ext;}public void setExt(String ext) {this.ext = ext;}}
取消
評(píng)論
總結(jié)
以上是生活随笔為你收集整理的android java服务端_Android/Java从服务器端下载图片的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 国家电网纪委教育整顿时间
- 下一篇: 姓胡属虎起什么网名好听