1. server code
Package demo.net; import Java. io. file; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. ioexception; import Java. io. inputstream; import java.net. datagrampacket; import java.net. datagramsocket; import java.net. socketexception; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors;/*** download server. UDP protocol may cause packet loss during transmission, the downloaded file is incomplete */public class downloadserver {// provides the public void Service () {try {// create a server with the specified port 8289 on the local machine; // thread pool, with 10 threads fixed: executorservice threadpool = executors. newfixedthreadpool (10); While (true) {// continuously receives requests from the client byte [] buff = new byte [101]; // The file name length cannot exceed 50 bytes rampacket datapacket = new bytes rampacket (buff, Buff. length); datasocket. receive (datapacket); // wait for receiving data packets from the client // receive the data packet, start a thread to serve the customer threadpool.exe cute (New workthread (datapacket);} catch (socketexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}}// internal class, which provides private class workthread implements runnable {private extends rampacket packet; private extends ramsocket datasocket; Public workthread (datagrampacket packet) {This. packet = packet; try {// create the ingress ramsocketdatasocket = new ingress ramsocket ();} catch (socketexception e) {e. printstacktrace () ;}}// obtain the list of files that can be downloaded and send it to the client private void showfiles () {file files = new file ("upload_download "); file [] allfile = files. listfiles (); // get all files stringbuffer message = new stringbuffer (); For (file F: allfile) {If (F. isfile () {message. append (F. getname (); message. append ('\ n') ;}// construct the response packet byte [] response = message. tostring (). getbytes (); datagrampacket datapacket = new datagrampacket (response, response. length, packet. getaddress (), packet. getport (); try {// send datasocket. send (datapacket);} catch (ioexception e) {e. printstacktrace () ;}/// download the specified file private void download (string filename) {try {inputstream in = new fileinputstream ("upload_download/" + filename); datagrampacket datapacket; byte [] response = new byte [60000]; // send 60000 bytes each time while (true) {int Len = in. read (response, 0, response. length); datapacket = new datagrampacket (response, Len, packet. getaddress (), packet. getport (); datasocket. send (datapacket); // send if (in. available () = 0) // The break is sent.} In. close ();} catch (filenotfoundexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}@ overridepublic void run () {// obtain the Data byte [] DATA = packet. getdata (); // indicates that the client clicks the show file button. This request is for obtaining all files that can be downloaded if (data [0] = 0) showfiles (); else if (data [0] = 1) // indicates that the client request is a download request (new string (data, 1, packet. getlength ()). trim (); elsesystem. out. println ("request error") ;}} public static void main (string [] ARGs) {New downloadserver (). service ();}}
Note: The initramsocket class is based on UDP protocol. By default, files downloaded on the server end are stored in the upload_download folder in the current directory. The server uses a thread pool to serve multiple users at the same time.
2. client code
Package demo.net; import Java. AWT. borderlayout; import Java. AWT. gridlayout; import Java. AWT. event. actionevent; import Java. AWT. event. actionlistener; import Java. io. file; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. outputstream; import java.net. datagrampacket; import java.net. datagramsocket; import java.net. inetaddress; import javax. swing. *;/*** download client */public class downloadclie NT extends jframe {// display the downloadable files private jtextarea textarea = new jtextarea (); Private jpanel Panel = new jpanel (); // save the file private jfilechooser SaveFile = new jfilechooser (". "); Private jbutton showbutton = new jbutton (" display file "); Private jbutton downloadbutton = new jbutton (" download... "); // enter the name of the file to be downloaded during the download process. Note that the file name must be the file name displayed in textarea: Private jtextfield downloadfile = new jtextfield (" "); Private datagramsocket datasock ET = NULL; Basic settings of Public downloadclient () {// frame this. settitle ("Download client"); this. setvisible (true); this. setdefaclocloseoperation (jframe. exit_on_close); this. setsize (400,500); this. setlayout (New borderlayout (); this. setresizable (false); // You Cannot edit textarea. seteditable (false); panel. setlayout (New gridlayout (3, 2, 5, 5); panel. add (New jlabel ("click to display downloadable files"); panel. add (showbutton); panel. add (downloadfile); panel. ad D (downloadbutton); // Add (New jscrollpane (textarea) to the frame; add (panel, borderlayout. south); // SaveFile can only open the SaveFile directory. setfileselectionmode (jfilechooser. directories_only); // display the file button to register the event showbutton. addactionlistener (New actionlistener () {@ overridepublic void actionreceivmed (actionevent e) {showbutton. setenabled (false); downloadbutton. setenabled (false); showfiles (); showbutton. setenabled (true); downloadbu Tton. setenabled (true) ;}}); // The Download button registers the event downloadbutton. addactionlistener (New actionlistener () {@ overridepublic void actionreceivmed (actionevent e) {showbutton. setenabled (false); downloadbutton. setenabled (false); downloadfile (); showbutton. setenabled (true); downloadbutton. setenabled (true) ;}}) ;}// display the private void showfiles () {try {If (datasocket = NULL) datasocket = new datagramsocket (); // create and send data packets to server B concurrently Yte [] request = {0}; datagrampacket requestpacket = new datagrampacket (request, request. length, inetaddress. getlocalhost (), 8289); datasocket. send (requestpacket); // receives server data packets, which are displayed in textarea byte [] receive = new byte [1024*1024]; datagrampacket implements epacket = new datagrampacket (receive, receive. length); datasocket. receive (receivepacket); string STR = new string (receivepacket. getdata (), 0, receivepacket. Getlength (); textarea. settext (STR);} catch (ioexception e) {e. printstacktrace () ;}/// download the private void downloadfile () {// get the file name to be downloaded string filename = downloadfile. gettext (). trim (); // all files that can be downloaded string allfiles = textarea. gettext (); // the file name is empty. If (filename = NULL | "". equals (filename) joptionpane. showmessagedialog (null, "Please select the correct file name", "file name error", joptionpane. warning_message); // the file name is else if (allfiles. Contains (filename + '\ n') {SaveFile. showsavedialog (null); file F = SaveFile. getselectedfile (); // obtain the selected folder if (F. exists () {// check whether the file already exists in the directory string [] filenames = f. list (); Boolean exit = false; For (string name: filenames) if (name. equals (filename) {exit = true; break;} If (exit) // if the file to be downloaded already has joptionpane. showmessagedialog (null, "this file already exists", "select another file to download", joptionpane. warning_message); else {// request sent Te [] request = (new string (New byte [] {1}) + filename ). getbytes (); try {If (datasocket = NULL) datasocket = new datagramsocket (); // create and send data packets to the server and send them to the server's datagrampacket requestpacket = new datagrampacket (request, request. length, inetaddress. getlocalhost (), 8289); datasocket. send (requestpacket); // receives server data packets and saves the file in the selected folder outputstream out = new fileoutputstream (F. getabsolutepath () + "/" + filename, true); BYT E [] receive = new byte [60000]; // receives 60000 bytes of datagrampacket receivepacket each time; // receives packets from the server while (true) {receiving epacket = new datagrampacket (receive, receive. length); datasocket. receive (paiepacket); out. write (paiepacket. getdata (), 0, receivepacket. getlength (); // The output stream outputs the file content to the file out. flush (); If (receivepacket. getlength ()! = Receive. length) break;} Out. close ();} catch (ioexception e) {e. printstacktrace () ;}} else // The selected folder does not exist. showmessagedialog (null, "select the Correct storage path", "Storage path error", joptionpane. warning_message);} else {// file name error joptionpane. showmessagedialog (null, "select the correct file name", "file name error", joptionpane. warning_message) ;}} public static void main (string [] ARGs) {New downloadclient ();}}
Note: When downloading a client, click "show file", enter the file name to be downloaded, click "Download", and select the Save path.
3. Start the server before running, and then open the client. Running result:
After you click on the display file and press enter to enter 01.jpg:
Click the Download button and select the Save path.
Click Save to download the file to the specified directory.