This example shares the specific code for Java implementation client to send files to the server for your reference. The specific content is as follows
Server source code:
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; /** * File name: ServerReceive.java * Implementation function: As a server, receive files sent by the client* * Specific implementation process: * 1. Establish SocketServer and wait for the client to connect* 2. When there is a client connection, according to the agreement between the two parties, you must read a line of data* which saves the file name and file size information to be sent by the client* 3. Create a file locally based on the file name and establish a streaming communication* 4. Receive the data packets in a loop and write the data packets to the file* 5. When the length of the received data is equal to the length of the file sent by the file in advance, it means that the file has been received and the file is closed* 6. The file reception work is over* * * * [Note: This code is only used to demonstrate that the client and the server transmit files, * There is no file protocol command before each packet* The specific phase of protocol transmission and file outflow can be placed by itself according to your own program] * * * Author: Xiaoqiu* Creation time: 2014-08-19 * * */ public class ServerReceive { public static void main(String[] args) { /**Communication handle to establish a connection with the server*/ ServerSocket ss = null; Socket s = null; /**Define file objects and file output stream objects created locally after reception*/ File file = null; FileOutputStream fos = null; /**Define input streams and use socket's inputStream to input the packet*/ InputStream is = null; /**Define byte arrays to serve as storage packets for packets*/ byte[] buffer = new byte[4096 * 5]; /**Stand string used to receive file sending requests*/ String comm = null; /**Set socekt communication and wait for the server to connect*/ try { ss = new ServerSocket(4004); s = ss.accept(); } catch (IOException e) { e.printStackTrace(); } /**Read the convention information sent by a line of clients*/ try { InputStreamReader isr = new InputStreamReader(s.getInputStream()); BufferedReader br = new BufferedReader(isr); comm = br.readLine(); } catch (IOException e) { System.out.println("The server disconnects from the client"); } /**Start parse the request command sent by the client*/ int index = comm.indexOf("/#"); /**Discuss whether the protocol is the protocol for sending files*/ String xieyi = comm.substring(0, index); if(!xieyi.equals("111")){ System.out.println("The protocol code received by the server is incorrect"); return; } /**Parse out the name and size of the file*/ comm = comm.substring(index + 2); index = comm.indexOf("/#"); String filename = comm.substring(0, index).trim(); String filesize = comm.substring(index + 2).trim(); /**Create an empty file to receive the file*/ file = new File(filename); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { System.out.println("The server side file creation failed"); } }else{ /** You can also ask whether to overwrite*/ System.out.println("The same file already exists in this path, overwrite"); } /** [The above is the prepared part of the server written in the client code] */ /** * The key code for the server to receive the file*/ try { /**Wrap the file into the file output stream object*/ fos = new FileOutputStream(file); long file_size = Long.parseLong(filesize); is = s.getInputStream(); /**size is the length of each received packet*/ int size = 0; /**count is used to record the length of the received file*/ long count = 0; /**Receive packets using while loop*/ while(count < file_size){ /**Read a packet from the input stream*/ size = is.read(buffer); /**Write the packet you just read to the local file*/ fos.write(buffer, 0, size); fos.flush(); /**The length of the received file +size*/ count += size; System.out.println("The server received the packet, the size is " + size); } } catch (FileNotFoundException e) { System.out.println("The server failed to write the file"); } catch (IOException e) { System.out.println("Server: Client disconnect"); } finally{ /** * Close the opened file* If necessary, you can also close the socket connection here* */ try { if(fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); }//catch (IOException e) }//finally }//public static void main(String[] args) }//public class ServerReceiveClient source code:
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.Socket; /** * * File name: ClientSend.java * Implementation function: Send a file to the server as a client* * Specific implementation process: * 1. Establish a connection with the server, IP: 127.0.0.1, port: 4004 * 2. Send the file name and size to the server through a custom file transfer protocol* 3. Read the local file loop and package the file to the data output stream* 4. Close the file and end the transmission* * [Note: This code is only used to demonstrate the file transfer between the client and the server. * There is no file protocol command before each data packet* The specific protocol transmission and file outgoing usage stage can be placed according to your own program] * * * Author: Novice* Creation time: 2014-08-19 * * */ public class ClientSend { public static void main(String[] args) { /**Communication handle to establish a connection with the server*/ Socket s = null; /**Define the file object, that is, the file to be sent* If you use an absolute path, don't forget to use the difference between '/' and '/'** For specific differences, please reader query by yourself* */ File sendfile = new File("API.CHM"); /**Define file input stream to open and read the file to be sent*/ FileInputStream fis = null; /**Define byte array to be used as the storage packet of the data packet*/ byte[] buffer = new byte[4096 * 5]; /**Define output stream and use socket's outputStream to output the packet*/ OutputStream os = null; /**Check whether the file to be sent exists*/ if(!sendfile.exists()){ System.out.println("Client: the file to be sent does not exist"); return; } /**Create a connection with the server*/ try { s = new Socket("127.0.0.1", 4004); } catch (IOException e) { System.out.println("Not connected to the server"); } /**Initialize the fis object with a file object* so that the file size can be extracted* */ try { fis = new FileInputStream(sendfile); } catch (FileNotFoundException e1) { e1.printStackTrace(); } /**First first send information about the file to the server to facilitate the server to receive related preparations* For specific preparations, please check the server code. * * The content sent includes: sending file protocol code (here is 111)/#file name (with suffix name)/#file size* */ try { PrintStream ps = new PrintStream(s.getOutputStream()); ps.println("111/#" + sendfile.getName() + "/#" + fis.available()); ps.flush(); } catch (IOException e) { System.out.println("Server connection interruption"); } /** * Sleep here for 2 seconds, waiting for the server to prepare the relevant work* Also to ensure network delay* Readers can choose to add this code* */ try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } /**After the previous preparation work is finished* The following is the key code for file transfer* */ try { /**Get the OutputStream of the socket to write a packet to it*/ os = s.getOutputStream(); /** size is used to record the size of each file read*/ int size = 0; /**Read the file using while loop until the file reading is finished*/ while((size = fis.read(buffer)) != -1){ System.out.println("The client sends the packet, the size is " + size); /**Write the packet you just read into the output stream*/ os.write(buffer, 0, size); /**Refresh*/ os.flush(); } } catch (FileNotFoundException e) { System.out.println("Client reading file error"); } catch (IOException e) { System.out.println("Client output file error"); } finally{ /** * Close the opened file* If necessary, you can also close the socket connection here* */ try { if(fis != null) fis.close(); } catch (IOException e) { System.out.println("Client file closing error"); }//catch (IOException e) }//finally }//public static void main(String[] args) }//public class ClientSendThe above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.