Java Network Programming Case 3: multiple clients to upload files

  Requirements: After the start of each client can upload a file to the server, upload saved to a directory server after receiving the file. The client may receive multiple file uploads simultaneously.

  analysis:

  (1) to the server "simultaneous" processing request multiple clients, you must use multiple threads, each of which communicates a client requires a separate thread to handle.

  (2) server directory where you saved the file to upload only one upload, and file for each client to the server may send the same name, so it is necessary to ensure unique file names. We can use the "time stamp" as the file name and extension unchanged

  (3) clients need to upload files to the server name (including extension) and the file contents. The file name is a string, not necessarily the content of the document as plain text, choosing DataOutputStream and DataInputStream.

  Client code examples:

 1 import java.io.BufferedReader;
 2 import java.io.DataOutputStream;
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.InputStream;
 6 import java.io.InputStreamReader;
 7 import java.io.OutputStream;
 8 import java.net.Socket;
 9 import java.util.Scanner;
10 
11 public class Client {
12     public static void main(String[] args) throws{Exception
 13 is          // (. 1) connected to the server 
14          the Socket Socket = new new the Socket ( "192.168.54.68", 8888 );
 15  
16          Scanner INPUT = new new Scanner (the System.in);
 . 17          
18 is          // (2) the file input from the keyboard path and name 
19          System.out.print ( "Please select a file to upload:" );
 20          String path = input.nextLine ();
 21          file file = new new file (path);
 22          
23          OutputStream OUT = Socket.getOutputStream ();
 24          the DataOutputStream DOS = new newThe DataOutputStream (OUT); // with its purpose is either to pass a single string, but also to write the contents of the byte
 25          
26 is          // to send the file name (including extension) 
27          dos.writeUTF (file.getName () ); // single send a string
 28          
29          // need an IO stream, read from the file, the server sends to the last 
30          the FileInputStream FIS = new new the FileInputStream (file);
 31 is                  
32          // (. 3) to the contents of the file the server passed in the past, similar to copy the file 
33 is          byte [] = Data new new  byte [1024 ];
 34 is          the while ( to true ) {
 35              int len = fis.read (Data);
 36              IF(len == -. 1 ) {
 37 [                  BREAK ;
 38 is              }
 39              dos.write (Data, 0 , len);
 40          }
 41 is          socket.shutdownOutput ();
 42 is          
43 is          // result (4) returned by the receiving server 
44 is          the InputStream IS = Socket.getInputStream ();
 45          the InputStreamReader ISR = new new the InputStreamReader (IS); // the character stream into a byte-stream 
46 is          the BufferedReader br = new new the BufferedReader (ISR);
 47          String Result = br.readLine ();
 48         System.out.println(result);
49         
50         //(5)关闭
51         fis.close();
52         input.close();
53         socket.close();
54     }
55 }

 

  Server sample code:

 1 import java.net.ServerSocket;
 2 import java.net.Socket;
 3 
 4 public class Server {
 5     public static void main(String[] args) throws Exception{
 6         //服务器在8888端口号监听数据
 7         @SuppressWarnings("resource")
 8         ServerSocket server = new ServerSocket(8888);
 9         
10         while(true){
11             //(2)等待连接 
12             //这句代码执行一次,意味着一个客户端连接
13             Socket accept = server.accept();
14         
15             FileUploadThread ft = new FileUploadThread(accept);
16             ft.start();
17         }
18     }
19 }

 

  服务器端处理每一个客户端上传文件的线程类代码:

 1 import java.io.DataInputStream;
 2 import java.io.FileNotFoundException;
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.io.OutputStream;
 7 import java.io.PrintStream;
 8 import java.net.Socket;
 9 import java.text.SimpleDateFormat;
10 import java.util.Date;
11 
12 public class FileUploadThread extends Thread{
13     private Socket socket;
14     private String dir = "upload/";
15 
16     public FileUploadThread(Socket socket) {
17         super();
18         this.socket = socket;
19     }
20     
21     public void run(){
22         FileOutputStream fos = null;
23         try {
24             InputStream is = socket.getInputStream();
25             DataInputStream dis = new DataInputStream(is);    
26             
27             //读取文件名(含后缀名)
28             String filename = dis.readUTF();
29             //截取后缀名
30             String ext = filename.substring(filename.lastIndexOf("."));
31             //生成时间戳
32             SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
33             filename = sf.format(new Date());
34             //用新文件路径构建文件输出流
35             fos = new FileOutputStream(dir + filename + ext);
36             //接收文件内容
37             byte[] data = new byte[1024];
38             while(true){
39                 int len = is.read(data);
40                 if(len==-1){
41                     break;
42                 }
43                 fos.write(data, 0, len);
44             }
45             
46             //返回结果
47             OutputStream out = socket.getOutputStream();
48             PrintStream ps = new PrintStream(out);
49             ps.println(filename + ext + ":已上传完毕");
50         } catch (FileNotFoundException e) {
51             e.printStackTrace();
52         } catch (IOException e) {
53             e.printStackTrace();
54         }finally{
55             try {
56                 fos.close();
57                 socket.close();
58             } catch (IOException e) {
59                 e.printStackTrace();
60             }
61         }
62     }
63 }

 

Guess you like

Origin www.cnblogs.com/niujifei/p/12291766.html