How to use Socket to realize File upload function in java
This article mainly introduces java how to use Socket to achieve file upload function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand it.
The details are as follows
To upload a file:
Server-side steps:
1. Create a ServerSocket
2. Call accept to get the client Socket
3. Define a byte array
4. Create a file output stream to get the client input stream
5. Read the bytes of the input stream in a loop and write them to the file output stream
Client steps:
1. Create a Socket
2. Get the output stream of socket object
3. Create a file input stream
4. Read the input stream bytes of the file in a loop and write them to the output stream
Code implementation:
Server side:
Public class FileServer {public static final int PORT = 8888; public static final String PATH = "D:\\ upload\"; public void start () {System.out.println ("start..."); try (/ / create server-side object ServerSocket server = new ServerSocket (PORT);) {while (true) {Socket socket = server.accept () Try (/ / create the file output stream and network input stream DataInputStream in = new DataInputStream (socket.getInputStream ()); / / read the file name sent by the short message, and create the file output stream FileOutputStream out = new FileOutputStream (PATH+in.readUTF ()) {int len = 0 Byte [] buffer = new byte [1024]; while ((len = in.read (buffer))! =-1) {out.write (buffer,0,len);} System.out.println ("Server saved!") ;} catch (IOException e) {e.printStackTrace ();}} public static void main (String [] args) {new FileServer () .start ();}}
Client:
Public class FileClient {/ * send file * / public void sendFile (String ip,int port,String path) {File file = new File (path); try (/ / create connection, create file input stream, network output stream Socket socket = new Socket (ip,port); InputStream in = new FileInputStream (path) DataOutputStream out = new DataOutputStream (socket.getOutputStream ()) {/ / first send the file to the server out.writeUTF (file.getName ()); out.flush (); / / read the local file and write it to the network output stream int len = 0; byte [] buffer = new byte [1024] While ((len = in.read (buffer))! =-1) {out.write (buffer,0,len);} System.out.println ("client sent complete!") ;} catch (UnknownHostException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}} public static void main (String [] args) {new FileClient (). SendFile ("192.168.31.226", 8888, "C:\ Users\\ admin\\ Desktop\ C.txt");}}
Achieve results:
Thank you for reading this article carefully. I hope the article "java how to use Socket to achieve file upload function" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!