使用socket进行服务端与客户端传文件的方法
逻辑:
1.客户端将需要查找的文件名以流的形式传给服务端
2.服务端接受客户端的连接,把流转化为字符串,进行一个目录的遍历,查找是否存在需要的文件,若未找到,则输出未找到,若找到,则将文件转化为流,传给客户端
3.客户端准备接受,将服务端传过来的流转化为文件,存储下载。
4,至此,完成一个简单的客户端与服务端传输文件的小栗子~
Client.Java
package com.ysk; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class Client { public static void main(String[] args) { try { Socket socket = new Socket("127.0.0.1", 5555); OutputStream os = socket.getOutputStream();// 字节输出流 PrintWriter pw = new PrintWriter(os); pw.write("aa.txt");//输入需要搜索的文件名 pw.flush(); socket.shutdownOutput(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String a = ""; String temp = ""; while ((temp = in.readLine()) != null) { a += temp; } PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream("src\\asb.txt"))); out.write(a); out.flush(); out.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } }
Server.java
package com.ysk; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { static ServerSocket serverSocket; public static void main(String[] args) { try { serverSocket = new ServerSocket(5555); System.out.println("***服务器即将启动,等待客户端的连接***"); Socket socket = serverSocket.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String file = br.readLine(); findFile("src", file); if (result) { System.out.println("已找到" + file); File f = new File(file); // File copyfile = new File("src\\file", "bb.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filepath + file))); System.out.println(filepath + file); String a = ""; String temp = ""; while ((temp = in.readLine()) != null) { a += temp; } PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); out.write(a); out.flush(); socket.shutdownOutput(); } else { System.out.println("未找到文件"); } } catch (IOException e) { e.printStackTrace(); } }
需自备aa.txt,这种资源文件,以便测试。
总结
以上所述是小编给大家介绍的使用socket进行服务端与客户端传文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
赞 (0)