直接代码不多说!
服务端:
package scoket.file.server; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.*;; public class FileServer { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { ServerSocket server = new ServerSocket(8888); Socket socket = new Socket(); while(true){ socket = server.accept(); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); byte[] b = new byte[1024]; //1、得到文件名 int a = is.read(b); String filename = new String(b, 0, a); System.out.println("接受到的文件名为:"+filename); String houzhui = filename.substring(filename.indexOf("."), filename.length()); String rand = String.valueOf((int) (Math.random() * 100000)); filename = rand+houzhui; System.out.println("新生成的文件名为:"+filename); FileOutputStream fos = new FileOutputStream("f:\\"+filename); int length = 0; while((length=is.read(b))!=-1){ //2、把socket输入流写到文件输出流中去 fos.write(b, 0, length); } //fos.flush(); fos.close(); os.flush(); os.close(); is.close(); socket.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
客户端
package scoket.file.client; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class FileCilent { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { Socket client = new Socket("192.168.3.28", 8888); InputStream is = client.getInputStream(); OutputStream os = client.getOutputStream(); String filepath="e:\\MyServer.java"; File file = new File(filepath); String filename = file.getName(); System.out.println("send's file name:"+filename); //1、发送文件名 os.write(filename.getBytes()); FileInputStream fis = new FileInputStream(file); byte[] b = new byte[1024]; int length = 0; while((length=fis.read(b))!=-1){ //2、把文件写入socket输出流 os.write(b, 0, length); } os.close(); fis.close(); is.close(); System.out.println("send over"); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }