The more I flee, the closer I get to you.
The more I recite my face, the more I see you.
I started from you,
I'm at your end.
Requirement: Implement socket transfer file under LAN.
Client steps:
1, establish a connection with the server
2. Create client output stream
3. Create an input stream and bind the file
4. Output to the server after reading the file
Server-Side steps:
1. Start the server
2. Create the Accept input stream
3. Create an output stream to bind the file
4. Read client information to local file
1. Byte stream transfer file.
1 Public classClient {2 3 Public Static voidMain (string[] args) throws IOException {4Socket client =NewSocket ("192.168.0.112",50000);5OutputStream OS =Client.getoutputstream ();6FileInputStream FIS =NewFileInputStream ("/home/yanshaochen/public/2017-05-06 15-12-02 screen. png");7 byte[] bytes =New byte[1024x768];8 intdata;9 while(data = fis.read (bytes))! =-1){TenOs.write (Bytes,0, data); One } A fis.close (); - client.close (); -System. out. println ("sent successfully!"); the } -}
1 Public classServer {2 3 Public Static voidMain (string[] args) throws Exception {4ServerSocket Server =NewServerSocket (50000);5System. out. println ("listening .");6Socket Accept =server.accept ();7InputStream is=Accept.getinputstream ();8FileOutputStream fos =NewFileOutputStream ("d:\\download\\ screen. png");9 byte[] bytes =New byte[1024x768];Ten intdata; One while(data = is. Read (bytes))!=-1){ AFos.write (Bytes,0, data); - } - fos.close (); the server.close (); -}
2. Character stream transfer file txt.
1 Public classClient {2 3 Public Static voidMain (string[] args) throws IOException {4 5Socket client =NewSocket ("192.168.0.112",50000);6OutputStream OS =Client.getoutputstream ();7Reader FR =NewFileReader ("/home/yanshaochen/public/zfsm.txt");8BufferedReader br =NewBufferedReader (FR);9 String buffer;Ten while(buffer = Br.readline ())! =NULL){ OneBuffer + ="\ r \ n"; A Os.write (Buffer.getbytes ()); - } - br.close (); the client.close (); -System. out. println ("sent successfully!"); - } -}
1 Public classServer {2 3 Public Static voidMain (string[] args) throws Exception {4 5ServerSocket Server =NewServerSocket (50000);6System. out. println ("listening .");7Socket Accept =server.accept ();8InputStream is=Accept.getinputstream ();9FileWriter FW =NewFileWriter ("D:\\download\\zfsm.txt");Ten byte[] bytes =New byte[1024x768]; One intdata; A while(data = is. Read (bytes))! =-1){ -Fw.write (NewString (Bytes,0, data)); - } the fw.close (); - server.close (); - } - +}
Java Learning note--socket for file transfer