使用socket进行服务端与客户端传文件的方法
程序员文章站
2024-02-23 16:35:10
逻辑:
1.客户端将需要查找的文件名以流的形式传给服务端
2.服务端接受客户端的连接,把流转化为字符串,进行一个目录的遍历,查找是否存在需要的文件,若未找到,则输出未找...
逻辑:
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进行服务端与客户端传文件的方法,希望对大家有所帮助
上一篇: Mybatis查询记录条数的实例代码
下一篇: ElasticSearch的完整安装教程