简单使用TCP协议,实现客户端和服务器端之间的文件和信息传输,并实现可以重复添加自定义文件的类型和名称.
//服务器端: public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(9990); while (true) { Socket socket = ss.accept(); 读,输入流 InputStream in = socket.getInputStream(); //写,输出 OutputStream out = socket.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); BufferedReader bf = new BufferedReader(new InputStreamReader(in)); //读取文件的名字. String s = bf.readLine(); System.out.println(s);//a.mp4; //给客户端一个反馈,告诉客户端自己已经看到文件名字了 bw.write("我已经看到文件名字了,可以上传文件了"); bw.newLine(); bw.flush(); String s1 = UUID.randomUUID().toString(); FileOutputStream fos = new FileOutputStream("Day16Class/"+s1+s); byte[] arr = new byte[1014 * 8]; int len; //使用in去读;fos来写 while ((len =in.read(arr))!=-1){ fos.write(arr,0,len); } bw.write("上传成功"); bw.newLine(); bw.flush(); } } ============================================
//客户端 public static void main(String[] args) throws IOException { Socket s = new Socket("127.0.0.1", 9990); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); BufferedReader bf = new BufferedReader(new InputStreamReader(in)); //第一步:获取文件名字 File file = new File("d:/dpcq.txt"); //获取文件名字 String name = file.getName(); //使用字符缓冲流写 bw.write(name); bw.newLine(); bw.flush(); //第二步: //得到服务器的反馈 String s1 = bf.readLine(); System.out.println(s1);//我已经看到文件名字了,可以上传文件了 //第三补:开始读取文件 FileInputStream fil = new FileInputStream(file); byte[] arr = new byte[1024 * 8]; int len; //写 while ((len = fil.read(arr)) != -1) { out.write(arr, 0, len); } //告诉服务器我已经读完了,不再读了 s.shutdownOutput(); String s2 = bf.readLine(); System.out.println(s2); }