Next, the previous article will be uploaded and downloaded.
5. Resuming breakpoint
For programmers who are familiar with QQ, QQ's breakpoint continuous transmission function should be very impressive. Because it's very practical and aspect. Therefore, during our upload and download process, the function of breakpoint continuous transmission is very well implemented.
In fact, the principle of breakpoint continuous transmission is very simple. During the upload process, go to the service to find out whether this file exists. If some files exist, compare the size of the file on the server with the size of the local file. If the files on the server are smaller than the local one, it is believed that breakpoint continuous transmission should be possible during the upload process of this file.
During implementation, the RandomAccessFile class becomes useful. Instances of this class support read and write to random access files. Random access files behave like a large byte array stored in the file system. There is a cursor or index pointing to the implicit array, called a file pointer; the input operation reads bytes from the file pointer and moves forward the file pointer as the byte is read. If the random access file is created in read/write mode, the output operation is also available; the output operation starts with the file pointer and advances the file pointer as the byte is written. An output operation after writing to the current end of an implicit array causes the array to expand. The file pointer can be read through the getFilePointer method and set through the seek method.
The skipBytes method of the RandomAccessFile class tries to skip n bytes input to discard the skipped bytes. If you find the size n of the file to be uploaded from the server, you can use the skipBytes method to skip these n bytes and start to perform breakpoint continuous transmission from a new place. For specific methods, please refer to the API description of JDK5.
You can see the implementation of uploading and downloading interrupt point continuous transmission in the run method of the dataConnection class. The code is as follows:
public void run() { try { newLine = con.getCRLF(); if(Settings.getFtpPasvMode()) { try { sock = new Socket(host, port); sock.setSoTimeout(Settings.getSocketTimeout()); } catch(Exception ex) { ok = false; debug("Can't open Socket on port " + port); } } else { //Log.debug("trying new server socket: "+port); try { ssock = new ServerSocket(port); } catch(Exception ex) { ok = false; Log.debug("Can't open ServerSocket on port " + port); } } } catch(Exception ex) { debug(ex.toString()); } isThere = true; boolean ok = true; RandomAccessFile fOut = null; BufferedOutputStream bOut = null; RandomAccessFile fIn = null; try { if(!Settings.getFtpPasvMode()) { int retry = 0; while((retry++ < 5) && (sock == null)) { try { ssock.setSoTimeout(Settings.connectionTimeout); sock = ssock.accept(); } catch(IOException e) { sock = null; debug("Got IOException while trying to open a socket!"); if(retry == 5) { debug("Connection failed, tried 5 times - maybe try a higher timeout in Settings.java"); } finished = true; throw e; } finally { ssock.close(); } debug("Attempt timed out, retrying"); } } if(ok) { byte[] buf = new byte[Settings.bufferSize]; start = System.currentTimeMillis(); int buflen = 0; //---------------download,下载---------------------- if(type.equals(GET) || type.equals(GETDIR)) { if(!justStream) { try { if(resume) { File f = new File(file); fOut = new RandomAccessFile(file, "rw"); fOut.skipBytes((int) f.length()); buflen = (int) f.length(); } else { if(localfile == null) { localfile = file; } File f2 = new File(Settings.appHomeDir); f2.mkdirs(); File f = new File(localfile); if(f.exists()) { f.delete(); } bOut = new BufferedOutputStream(new FileOutputStream(localfile), Settings.bufferSize); } } catch(Exception ex) { debug("Can't create outputfile: " + file); ok = false; ex.printStackTrace(); } } //---------------upload,上传---------------------- if(type.equals(PUT) || type.equals(PUTDIR)) { if(in == null) { try { fIn = new RandomAccessFile(file, "r"); if(resume) { fIn.skipBytes(skiplen); } //fIn = new BufferedInputStream(new FileInputStream(file)); } catch(Exception ex) { debug("Can't open inputfile: " + " (" + ex + ")"); ok = false; } } if(ok) { try { out = new BufferedOutputStream(sock.getOutputStream()); } catch(Exception ex) { ok = false; debug("Can't get OutputStream"); } if(ok) { try { int len = skiplen; char b; while(true) { int read; if(in != null) { read = in.read(buf); } else { read = fIn.read(buf); } len += read; //System.out.println(file + " " + type+ " " + len + " " + read); if(read == -1) { break; } if(newLine != null) { byte[] buf2 = modifyPut(buf, read); out.write(buf2, 0, buf2.length); } else { out.write(buf, 0, read); } con.fireProgressUpdate(file, type, len); if(time()) { // Log.debugSize(len, false, false, file); } if(read == StreamTokenizer.TT_EOF) { break; } } out.flush(); //Log.debugSize(len, false, true, file); } catch(IOException ex) { ok = false; debug("Error: Data connection closed."); con.fireProgressUpdate(file, FAILED, -1); ex.printStackTrace(); } } } } } } } catch(IOException ex) { Log.debug("Can't connect socket to ServerSocket"); ex.printStackTrace(); } finally { try { if(out != null) { out.flush(); out.close(); } } catch(Exception ex) { ex.printStackTrace(); } try { if(bOut != null) { bOut.flush(); bOut.close(); } } catch(Exception ex) { ex.printStackTrace(); } try { if(fOut != null) { fOut.close(); } } catch(Exception ex) { ex.printStackTrace(); } try { if(in != null && !justStream) { in.close(); } if(fIn != null) { fIn.close(); } } catch(Exception ex) { ex.printStackTrace(); } } try { sock.close(); } catch(Exception ex) { debug(ex.toString()); } if(!Settings.getFtpPasvMode()) { try { ssock.close(); } catch(Exception ex) { debug(ex.toString()); } } finished = true; if(ok) { con.fireProgressUpdate(file, FINISHED, -1); } else { con.fireProgressUpdate(file, FAILED, -1); } } 6. FTP port mapping
There are two types of FTP data connections: PASV and PORT. If your FTP server is located in the intranet, you need to use port mapping. At the beginning, I didn’t know much about FTP’s external network mapping, so I started to take a lot of detours. At first, I always thought that there was something wrong with my program and wasted a lot of time. I hope that through this period, everyone can spend less or no unnecessary time and energy during development.
There was an article on PCD that introduced a method to directly access the intranet. In fact, as long as we use the port mapping tool, we can easily achieve the purpose of penetrating the intranet. "Port Mapper" is such a tool. What is more worth mentioning is that it gets rid of the command line mode and provides a graphical interface operating environment.
In order to make everyone understand more, let me talk about the principle first. Suppose there is now a LAN with the host A. In addition to the host, there is also a machine in the LAN with B. Of course, the B machine is surfing the Internet through host A. There is also a machine that can access the Internet, which is not in the same LAN as A and B. Normally, machine C can only access host A, but cannot penetrate the LAN and access B. After port mapping, when machine C accesses the specified port of host A, the "port mapper" on host A works. It will transfer the data on the specified port to the specified port of another machine in the LAN, thereby achieving the purpose of accessing the intranet machine. Saying this way, everyone understands. As for how to configure it, the author believes that it should not be a difficult task. Besides, there are many such graphic explanations on the Internet. Please refer to the articles on the Internet for setting up.
Of course, the advantages of realizing direct access to the intranet are obvious. Not to mention anything else, at least FTP resources are fully utilized. However, it must be reminded that direct access to the intranet may threaten the security of the intranet. The author believes that most friends still attach importance to the importance of host security, but they often ignore the security settings of intranet machines. Once you have achieved direct access to the intranet, you must treat the intranet machines like a host, otherwise your entire network may be in danger.
Access client resources
The security policy of the Java application environment, which is expressed by a Policy object for the permissions of different resources owned by different codes. In order for Applet (or an application running under SecurityManager) to perform protected behaviors, such as reading and writing files, Applet (or Java applications) must obtain permission for that operation, and the security policy file is used to implement these permissions.
A Policy object may have multiple entities, although only one can work at any time. The currently installed Policy object can be obtained in the program by calling the getPolicy method or changed by calling the setPolicy method. The Policy object evaluates the entire policy, returning an appropriate Permissions object that details which code can access which resources. Policy files can be stored in unformatted ASCII files or in binary files or databases of Policy class. This article only discusses the form of unformatted ASCII files.
In actual use, we don’t need to manually write such complex java.policy files, especially when we don’t use digital signatures. At this time, we can completely learn from the ready-made C:/Program Files/Java/jre1.5.0_12/lib/security/java.policy file provided to us by JRE, and make corresponding modifications according to our needs. This article will write a security policy file for the situation where digital signatures are not used. Below is a complete java.policy file used under Windows NT/XP. In the file, the purpose of each "permission" record is explained separately using comments. Of course, different programs may have different requirements for resource access rights, and can be adjusted and selected according to project needs.
grant { //Permission to "read" the system and user directory permission java.util.PropertyPermission "user.dir", "read"; permission java.util.PropertyPermission "user.home", "read"; permission java.util.PropertyPermission "java.home", "read"; permission java.util.PropertyPermission "java.home", "read"; permission java.util.PropertyPermission "java.class.pat", "read"; permission java.util.PropertyPermission "user.name", "read"; //Operation permissions on threads and thread groups permission java.lang.RuntimePermission "accessClassInPackage.sun.misc"; permission java.lang.RuntimePermission "accessClassInPackage.sun.audio"; permission java.lang.RuntimePermission "modifyThread"; permission java.lang.RuntimePermission "modifyThreadGroup"; permission java.lang.RuntimePermission "loadLibrary.*"; //Permission to read and write files permission java.io.FilePermission "<<ALL FILES>>", "read"; permission java.io.FilePermission "${user.dir}${/}jmf.log", "write"; permission java.io.FilePermission "${user.home}${/}.JMStudioCfg", "write"; permission java.net.SocketPermission "*", "connect,accept"; permission java.io.FilePermission "C:/WINNT/TEMP/*", "write"; permission java.io.FilePermission "C:/WINNT/TEMP/*", "delete"; permission java.awt.AWTPermission "showWindowWithoutWarningBanner"; permission javax.sound.sampled.AudioPermission "record"; // // Various permissions for operating Socket ports permission java.net.SocketPermission "-", "listen"; permission java.net.SocketPermission "-", "accept"; permission java.net.SocketPermission "-", "connect"; permission java.net.SocketPermission "-", "resolve"; permission java.security.AllPermission; }; grant signedBy "saili" { permission java.net.SocketPermission "*:1024-65535", "connect,accept,resolve"; permission java.net.SocketPermission "*:80", "connect"; permission java.net.SocketPermission "-", "listen, accept, connect, listen, resolve", signedBy "ganja"; permission java.net.SocketPermission "-", "accept"; permission java.net.SocketPermission "-", "connect"; permission java.net.SocketPermission "-", "resolve"; permission java.security.AllPermission; }; In this project, in order to make it more convenient and simple to use the client user settings, the above file is made into a small program using VB or C#. Then combine JRE and some exes into an EXE package. After the JRE is installed, this applet is responsible for finding the installation path of JRE in the operating system, and write out the java.policy file in the program to overwrite the original file. In this way, the user only needs to install an EXE file, which simplifies the number of installation operations.
7. Applet callback server
The ability of JavaScript and Applet to communicate with each other brings us a lot of convenience. Java and JavaScript complement each other to develop more perfect web applications. B/S can make full use of the advantages of java, bringing us more network experience and making it convenient for users. The author uses more applications developed by Swing components to implement B/s architecture using Applet, which can fully demonstrate the advantages of Swing components, facilitate system upgrades and maintains; in addition, under WEB, sometimes the client needs to use local hardware resources. What I know is that it is implemented through Applet and calls java API through Applet. Let’s take a look at how JavaScript and Applet communicate in detail?
1.JavaScript access to Applet
<applet name="appletName" ....///JavaScript accesses Applet properties.
window.document.appletName.appletField (the property must be public, "window.document." can also be written without writing) //JavaScript access to Applet method.
window.document.appletName.appletMethod (the method must be public, "window.document." can also be written without writing).
2.Applet access to JavaScript
Live Connect provides an interface between Java and JavaScript, which allows JavaScript to be used in Java Applet applets.
You need to use a jar package, and look for it in the C:/Program Files/Java/ directory. It is about 5M. In fact, it is just to open it to see which one has netscape.javascript.JSObject. If you don't have NetScape installed or you can do it online or offline. You can rename it to netscape.jar (not necessary), and must be added to classpath, with the purpose of making it compiled during development. It is particularly important to note that netscape.jar is not required to be included during deployment, because the entire package will be downloaded to the client, affecting the speed.
//Introduce the netscape class import netscape.javascript.JSObject; import netscape.javascript.JSException; //It can be allowed to handle exception events in applets public void callJavaScript(String callBackJavascript) { JSObject window = JSObject.getWindow(this); // Get the JavaScript window handle and refer to the current document window JSObject document = (JSObject) window.getMember("document"); form=(JSObject)doc.getMember("textForm"); //Access the JavaScript form object textField=(JSObject)form.getMember("textField"); access the JavaScript text object text=(String) textField.getMember("value"); //Get the value of the text area// Call JavaScript's alert() method// window.eval("alert(/"This alert comes from Java!/")"); window.call(callBackJavascript, null);// The parameters are represented in the form of an array. }8. Operation effect
1. Upload
(1). Start uploading
(2). Uploading
(3). Uploading
(4). Upload successfully
2. download
(1) Save path of download file
(2) Downloading
(3) Downloading
(4) Download successfully
9. Summary
In this article, the author will explain the solution to the upload and download problem in actual projects, and use the FTP protocol to achieve batch, basic web large files upload and download. At the same time, it can access local resources on the client through Applet technology. A preliminary discussion was conducted on some of the actual functions that people often encounter, such as progress bar, breakpoint continuous transmission, FTP internal and external network mapping, etc. This is the basic application of the author based on some FTP Java client libraries. I hope it will be a reference for readers. Supplement some of these unfinished matters. There are also some contents that are relatively easy and have descriptions or examples online that are not listed here. For example, how FTP can establish FTP services on the server-side Serv-U software, how Applets are embedded in JSP pages and parameter delivery methods, and how Applets are started under Eclipse or NetBeans, due to space limitations, there is no detailed description. Please refer to the examples or other reference materials on the Internet.
Download address: http://xiazai.VeVB.COM/201608/yuanma/FTPTransfer(VeVB.COM).rar
Note: Considering the copyright issue, the JAVA class file was not sent up, but I think everyone is already familiar with how to restore such a JAR file to a java file, haha.
The 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.