以前没写过socket传输文件,上网查了一些资料。写了一个,哪里写的不对请大家多多指教。
// 服务端代码是用的mina写的 // 其实用socket也一样,只是关建字不一样而且己 public static void main(String[] args){ File f = null; FileInputStream fin = null; FileChannel fc = null; String[] datas = data.split(","); String fileName = args[1]; // 文件名 IoSession session = getSession(); try { f = new File("D:\\"+fileName); if(!f.isFile()){ // 判断是否找到文件 session.write("File does not exist!"); return null; } fin = new FileInputStream(f); // 读文件流 fc = fin.getChannel(); // 得到文件流通道 while (true) { ByteBuffer bb = ByteBuffer.allocate(1024); int i = fc.read(bb); if (i < 0) { break; } IoBuffer ib = IoBuffer.wrap(bb); ib.flip(); session.write(ib); // 不间断发送会导致buffer异常 Thread.sleep(5); } fc.close(); fin.close(); } catch (Exception e) { e.printStackTrace(); } finally{ session.close(false); } }
public static void main(String[] args) { Socket s = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; OutputStream os = null; try { s = new Socket("localhost", 6000); bis = new BufferedInputStream(s .getInputStream()); bos = new BufferedOutputStream(new FileOutputStream("D:\\test.rar")); os = s.getOutputStream(); os.write("%%Cmd,Cmd.rar,!!".getBytes());// 发送指令 要求服务端发送文件为 Cmd.rar byte[] buf = new byte[8192]; int len = 0; while ((len = bis.read(buf, 0, 8192)) != -1) { bos.write(buf, 0, len); } bos.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ try { bos.close(); bis.close(); s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }