Android网络编程之Socket方式上传对象序列化文件(服务器端)
服务器端分为两个类,主类与线程类,每有一个客户端连接,就新启动一个线程,这样就可以接收多个客户端的连接
主类:
初始化ServerSocket,并设定端口号 ---> 监听客户端连接,启动线程处理
1 import java.io.IOException; 2 import java.net.ServerSocket; 3 4 public class UploadServer { 5 private static boolean flag = true; 6 7 public static void main(String[] args ) { 8 try { 9 ServerSocket server = new ServerSocket(9999); 10 while (flag) { 11 // 每有一个客户端连接, 新起一个线程类处理,这样可以进行多客户端连接 12 new Thread(new UploadThread(server.accept())).start(); 13 } 14 } catch (IOException e) { 15 e.printStackTrace(); 16 } 17 18 } 19 }
线程类:
启动时实例化客户端Socket,并设定好服务器端储存文件路径 ---> 取得对象输入流(接收客户端数据),输出流(回应客户端)---> 调用saveFile()方法把接收到数据存到服务器端
1 public class UploadThread implements Runnable { 2 3 private Socket client = null; 4 private File file = null; 5 private UploadFile uploadFile = null; 6 7 private String filePath = "D:" + File. separator + "Doc" 8 + File.separator + "Image" 9 + File.separator + "Pic" ; 10 11 public UploadThread(Socket client) { 12 this.client = client; 13 } 14 15 @Override 16 public void run() { 17 if (client .isConnected()) { 18 System. out.println("connect!" ); 19 } 20 21 // 取得服务器端对象输入流,打印输出流 22 PrintStream ps = null; 23 ObjectInputStream ois = null; 24 try { 25 ps = new PrintStream(client .getOutputStream()); 26 ois = new ObjectInputStream(client .getInputStream()); // 反序列化 27 uploadFile = (UploadFile) ois.readObject(); // 读入客户端发送过来的对象序列 28 29 // 检测接收到的序列对象信息 30 System.out.println( "文件名: " + uploadFile.getTitle()); 31 System.out.println( "文件类型: " + uploadFile.getMimeType()); 32 System.out.println( "文件大小: " + uploadFile.getContentLength()); 33 34 // 调用方法保存文件到本地路径 35 ps.print(saveFile()); 36 } catch (IOException e) { 37 e.printStackTrace(); 38 } catch (ClassNotFoundException e) { 39 e.printStackTrace(); 40 } finally { 41 try { 42 if (ois != null) { 43 ois.close(); 44 ois = null; 45 } 46 if (ps != null) { 47 ps.close(); 48 ps = null; 49 } 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 } 54 }
saveFile()方法:
检测路径是否存在 ---> 取得文件输出流输出
1 private boolean saveFile() { 2 // 设置服务器端接收文件路径(使用UUID类给出一个独一无二的文件名) 3 file = new File(filePath + UUID. randomUUID() + "." + uploadFile.getExt()); 4 if (!file .getParentFile().exists()) { 5 file.mkdirs(); 6 } 7 8 // 取得文件输出流 9 FileOutputStream fos = null; 10 try { 11 fos = new FileOutputStream(file ); 12 fos.write( uploadFile.getData()); 13 return true; 14 } catch (FileNotFoundException e) { 15 e.printStackTrace(); 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } finally { 19 try { 20 if (fos != null) { 21 fos.close(); 22 fos = null; 23 } 24 } catch (IOException e) { 25 e.printStackTrace(); 26 } 27 } 28 return false; 29 } 30 31 }