package netFile; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; public class SocketTask { //客户端发送文件 public static void main(String[] args) { Socket socket = null; BufferedInputStream bis = null; BufferedOutputStream bos= null; try { socket = new Socket("127.0.0.1", 10086); bis = new BufferedInputStream(new FileInputStream("f:"+File.separator+"2.jpg")); bos = new BufferedOutputStream(socket.getOutputStream()); byte [] buffer = new byte[1024]; int len = 0; while((len = bis.read(buffer)) != -1){ bos.write(buffer, 0, len); bos.flush(); } socket.shutdownOutput(); System.out.println("客户端发送完成 !"); BufferedInputStream is = new BufferedInputStream(socket.getInputStream()); is.read(); } catch (IOException e) { e.printStackTrace(); }finally{ close(bis); close(bos); } } private static void close(Closeable close){ if(close != null){ try { close.close(); } catch (IOException e) { e.printStackTrace(); } } } }
package netFile; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class SeverSocketTask { //服务端,接收文件 public static void main(String[] args) { ServerSocket sc = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { sc = new ServerSocket(10086); Socket socket = sc.accept(); bis = new BufferedInputStream(socket.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream("e:"+File.separator+"aa.jpg")); byte [] buffer = new byte[1024]; int len = 0; while((len = bis.read(buffer)) != -1){ bos.write(buffer, 0, len); bos.flush(); } BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); writer.write("服务端已收到消息!"); writer.flush(); socket.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); }finally{ close(bos); } } private static void close(Closeable close) { if(close != null){ try { close.close(); } catch (IOException e) { e.printStackTrace(); } } } }
时间: 2024-10-08 12:42:39