这篇文章给大家介绍服务端与客户端怎么利用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(); } }
关于服务端与客户端怎么利用socket传文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。