逻辑:
2.服务端接受客户端的连接,把流转化为字符串,进行一个目录的遍历,查找是否存在需要的文件,若未找到,则输出未找到,若找到,则将文件转化为流,传给客户端
3.客户端准备接受,将服务端传过来的流转化为文件,存储下载。
4,至此,完成一个简单的客户端与服务端传输文件的小栗子~
Client.Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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 { 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
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进行服务端与客户端传文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:http://blog.csdn.net/ysk_xh_521/article/details/77356022