Example of Java using socket communication to transfer files

This article gives an example of how Java uses socket communication to transfer files. Share with you for your reference, as follows:

The previous articles introduced socket programming using Java and the application of NiO package in socket. This article talks about how to use socket programming to realize simple file transfer.

Since the previous article introduced the application of NiO in socket, NiO package continues to be used when reading and writing files, so the code looks a little more complex than the direct use of stream.

The following example shows that the client sends a file to the server, and the server sends a file back to the client in response. Here we prepare two files e: / test / server_ send. Log and E: / test / client send. Log file. After the test, there will be two more files e: / test / server in the same directory of the client and server_ receive. Log and E: / test / client receive. Log file.

Let's first look at the server class, focusing on the sendfile and receivefile methods.

The following is the client program code, which also focuses on the sendfile and receivefile methods

First run myserver4 class to start listening, and then run myclient4 class to send files to the server and accept server response files. After running, check the files received by the server and client respectively.

Readers interested in more Java related content can view the special topics of this site: summary of java socket programming skills, summary of java file and directory operation skills, tutorial on Java data structure and algorithm, summary of Java DOM node operation skills and summary of Java cache operation skills

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>