The Socket communication mechanism and JavaIO stream are adopted to upload large files between two Java servers. The specific ideas are as follows:
Implementation idea:
1, service: use ServerSocket to build the server, open the corresponding port, long connection operation
2, server: use serversocket.accept () method to block, receive the client request
3, server: every time a Socket is received, create a new thread to process it
4, customer: remote connection using Socket, inquire the upload progress
Skip (long length) reads the file from the specified location and sends the file stream to the server
6, service: receive the client input stream, use RandomAccessFile. Seek (long length) random read, move the cursor to the specified position for reading and writing
7, customer/service: a cycle output, a cycle read and write
8, example: the following is the specific code for reference only
Introduction to the document:
Fileuploadserver.java (Server receive file class)
Fileuploadclient.java (client send file class)
Finalvariable.java (custom parameter classes)
SocketServerListener. Java (JavaWeb start Socket operation class)
Web.xml (configuration file, following project startup)
Breakpoint upload (server)
package com.cn.csdn.seesun2012.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.math.RoundingMode;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
public class FileUpLoadServer extends ServerSocket {
// File size
private static DecimalFormat df = null;
// Exit the identifier
private boolean quit = false;
static {
// Set the number format, reserving one decimal place
Df = new DecimalFormat (” # 0.0 “);
df.setRoundingMode(RoundingMode.HALF_UP);
df.setMinimumFractionDigits(1);
df.setMaximumFractionDigits(1);
}
public FileUpLoadServer(int report) throws IOException {
super(report);
}
/ * *
* Use threads to process files transferred by each client
* @throws Exception
* /
public void load() throws Exception {
System.out.println(” this.getinetAddress () + “running… );
while (! quit) {
// The server tried to receive connection requests from other sockets. The server’s Accept method was blocked
Socket socket = this.accept();
/ * *
* Our server processes the connection request from the client synchronously. Each time we receive a connection request from the client,
* The next connection request can be processed only after the current client has finished communicating with it. This can seriously affect program performance in the case of high concurrency,
* To do this, we can change it to handle communication with the client asynchronously as follows
* /
// The request is received, and the validity is verified
String ip = socket.getInetAddress().toString();
ip = ip.substring(1, ip.length());
System.out.println(” The server received the request and is enabling the validation IP: “+ IP +”! );
// Every time a Socket is received, a new thread is created to process it
new Thread(new Task(socket, ip)).start();
}
}
/ * *
* Handle file thread classes transferred from the client
* /
class Task implements Runnable {
private Socket sk; // Current connection
private String ips; // Current connection IP address
public Task(Socket socket, String ip) {
this.sk = socket;
this.ips = ip;
}
public void run() {
Socket socket = sk; // Redefine, do not move outside of the run() method, otherwise the connection will be reset
String ip = ips; // Redefine, same as above IP will change
long serverLength = -1l; // Definition: the length of the file stored on the server, default is not -1
char pathChar = File.separatorChar; // Get: system path separator
String panFu = “D:”; // Path: drive letter for storing files
DataInputStream dis = null; // Get: client output stream
DataOutputStream dos = null; // Send: input stream to client
FileOutputStream fos = null; // Read: server local file stream
RandomAccessFile rantmpfile = null; // Operation class: random read
try {
/ / to get
dis = new DataInputStream(socket.getInputStream());
/ / send
dos = new DataOutputStream(socket.getOutputStream());
// Define the file name passed by the client
String fileName = “”;
while (fileName == “”) {
// Read the data from the client
fileName = dis.readUTF();
System.out.println(” server gets client fileName: “+ fileName);
File file = new File(panFu+ pathChar +”receive”+ pathChar +”” + ip + pathChar + fileName);
if (file.exists()) {
serverLength = file.length();
dos.writeLong(serverLength);
System.out.println(” Return file length to client: “+ serverLength +” B”);
} else {
serverLength = 0l;
dos.writeLong(serverLength);
System.out.println(” file does not exist “);
System.out.println(” Return file length to client: “+ serverLength +” B”);
}
}
System.out.println(” server creates new thread to handle client request, IP: “+ IP +”, transfer in progress…” );
// Get the input stream from the client
dis = new DataInputStream(socket.getInputStream());
// File name and length
long fileLength = dis.readLong();
File directory = new File(panFu + pathChar + “receive”+ pathChar +”” + ip + pathChar);
if (! directory.exists()) {
directory.mkdirs();
}
int length = 0;
byte[] bytes = new byte[1024];
File file = new File(directory.getAbsolutePath() + pathChar + fileName);
if (! file.exists()) {
/ / does not exist
fos = new FileOutputStream(file);
// Start receiving files
while ((length = dis.read(bytes, 0, bytes.length)) != -1) {
fos.write(bytes, 0, length);
fos.flush();
}
} else {
// The length of the file stored in the server
long fileSize = file.length(), pointSize = 0;
// Check whether the download is complete
if (fileLength > fileSize) {
// Breakpoint download
pointSize = fileSize;
} else {
// Download it again
file.delete();
file.createNewFile();
}
rantmpfile = new RandomAccessFile(file, “rw”);
/ *
- Java.io.inputstream.skip () Usage: skip n bytes (discard) if n
If * is negative, no bytes are skipped.
* /
// dis.skip(pointSize); (Progress read from client)
/ * *
* Resource, file location (cursor, pointer) Set the pointer to RAS to 8 and read and write ras from the ninth byte to
* /
rantmpfile.seek(pointSize);
while ((length = dis.read(bytes, 0, bytes.length)) != -1) {
rantmpfile.write(bytes, 0, length);
}
}
System.out.println(“======== File received successfully [File Name :” + fileName + “] [ClientIP:” + IP + “] [Size: ” + getFormatFileSize(file.length()) + “] ========”);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos ! = null)
fos.close();
if (dis ! = null)
dis.close();
if (rantmpfile ! = null)
rantmpfile.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println(” Failed to close Socket!” );
}
/ * *
* After the file is transferred, perform subsequent operations (omitted).
* /
//DoSomeThing dst = new DoSomeThing()
//dst.save(filePath);
}
}
}
/ * *
* Format file size
* @param length
* @return
* /
public String getFormatFileSize(long length) {
double size = ((double) length) / (1 << 30);
if (size >= 1) {
return df.format(size) + “GB”;
}
size = ((double) length) / (1 << 20);
if (size >= 1) {
return df.format(size) + “MB”;
}
size = ((double) length) / (1 << 10);
if (size >= 1) {
return df.format(size) + “KB”;
}
return length + “B”;
}
/ * *
* out
* /
public void quit() {
this.quit = true;
try {
this.close();
} catch (IOException e) {
System.out.println(” Server shutdown exception, cause unknown “);
}
}
}
Breakpoint upload (client)
package com.cn.csdn.seesun2012.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/ * *
- The Client side
* File upload (breakpoint) transmission
* @author CSDN:seesun2012
-
@createdate August 18, 2017
-
Override November 07, 2017
* @ version 1.1
* /
public class FileUpLoadClient extends Socket{
private Logger logger = LoggerFactory.getLogger(“oaLogger”);
private Socket client; // Socket- client
private static long status = 0; / / the progress bar
private boolean quit = false; / / exit
/ * *
* the constructor
* @param IP Indicates the IP address of the server
* @param Report Server open port
* @throws UnknownHostException
* @throws IOException
* /
public FileUpLoadClient(String ip, Integer report) throws UnknownHostException, IOException {
super(ip, report);
this.client = this;
if (client.getLocalPort()>0) {
System.out.println(“Cliect[port:” + client.getLocalPort() + “] successfully connect to server “);
}else{
System.out.println(” server connection failed “);
}
}
public int sendFile(String filePath) {
DataOutputStream dos = null; // Upload server: output stream
DataInputStream dis = null; // Get server: input stream
Long serverLength = -1l; // The length of the file stored on the server, default -1
FileInputStream fis = null; // Read file: input stream
// Get: upload the file
File file = new File(filePath);
/ / = = = = = = = = = = = = = = = = = = = = nodes: file exists = = = = = = = = = = = = = = = = = = = =
if (file.exists()) {
// Send: file name, file length
try {
dos = new DataOutputStream(client.getOutputStream());
} catch (IOException e2) {
Logger. error(“Socket client: 1. Error reading output stream “);
e2.printStackTrace();
}
try {
dos.writeUTF(file.getName());
dos.flush();
dos.writeLong(file.length());
dos.flush();
} catch (IOException e2) {
Logger. error(“Socket client: 2. Sending file name, length error “);
e2.printStackTrace();
}
// Get: Length of uploaded file
try {
dis = new DataInputStream(client.getInputStream());
} catch (IOException e2) {
Logger. error(“Socket client: 3. Sending file name, length error “);
e2.printStackTrace();
}
while(serverLength==-1){
try {
serverLength = dis.readLong();
} catch (IOException e) {
Logger. error(“Socket client: 4. Read server length send error “);
e.printStackTrace();
}
}
// Read: the file to be uploaded
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e2) {
Logger. error(“Socket client: 5. Failed to read the file that needs to be uploaded locally, please check whether the file exists “);
e2.printStackTrace();
}
// Send: transmits the input stream to the server
try {
dos = new DataOutputStream(client.getOutputStream());
} catch (IOException e2) {
Logger. error(“Socket client: 6. Error sending input stream to server “);
e2.printStackTrace();
}
System.out.println(“======== start file transfer ========”);
byte[] bytes = new byte[1024];
int length = 1024;
long progress = serverLength;
// Set cursor: file read position
if (serverLength==-1l) {
serverLength = 0l;
}
try {
fis.skip(serverLength);
} catch (IOException e1) {
Logger. error(“Socket client: error setting cursor position, please check whether file stream is tampered with “);
e1.printStackTrace();
}
try {
while (((length = fis.read(bytes, 0, bytes.length)) ! = -1) && quit ! = true) {
dos.write(bytes, 0, length);
dos.flush();
progress += length;
status = (100 * progress / file.length());
}
} catch (IOException e) {
Logger. error(“Socket client: 8. Error setting cursor position, please confirm whether file stream has been tampered with “);
e.printStackTrace();
}finally {
if (fis ! = null)
try {
fis.close();
} catch (IOException e1) {
Logger. error(“Socket client: 9.
e1.printStackTrace();
}
if (dos ! = null)
try {
dos.close();
} catch (IOException e1) {
Logger. error(“Socket client: 10.
e1.printStackTrace();
}
try {
client.close();
} catch (IOException e) {
Logger. error(“Socket client: 11. Closing client exception “);
e.printStackTrace();
}
}
System.out.println(“======== file transfer successful ========”);
}else{
Logger. error(“Socket client: 0. File does not exist “);
return -1;
}
return 1;
}
/ * *
* the progress bar
* /
public void statusInfo(){
Timer time = new Timer();
time.schedule(new TimerTask() {
long num = 0;
@Override
public void run() {
if (status>num) {
System.out.println(” status+”);
num = status;
}
if (status==101) {
System.gc();
}
}
},0,100);
}
/ * *
* out
* /
public void quit() {
this.quit = true;
try {
this.close();
} catch (IOException e) {
System.out.println(” Server shutdown exception, cause unknown “);
}
}
}
Breakpoint upload (Parameter Settings)
package com.cn.csdn.seesun2012.socket;
public interface FinalVariables {
// Server IP address
Public final static String SERVER_IP = “192.168.1.10010”;
// Server port
public final static int SERVER_PORT = 10086;
// Enable configuration
public final static String IS_START_SERVER = “instart”;
}
Breakpoint upload (JavaWeb startup server)
package com.cn.csdn.seesun2012.socket;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
/ * *
- The Server side
* Function description: server listening to open Servlet
* @author CSDN:seesun2012
-
@createdate August 18, 2017
-
Override November 07, 2017
-
Override November 14, 2017
* @ version 1.3
* /
public class SocketServerListener extends HttpServlet{
private static final long serialVersionUID = -999999999999999999L;
// Initialize the Socket service
@Override
public void init() throws ServletException {
super.init();
for(int i = 0; i < 3; i++){
if (“instart”.equals(FinalVariables.IS_START_SERVER )) {
open();
break;
}
}
}
public void open(){
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@SuppressWarnings(“resource”)
@Override
public void run() {
try {
FileUpLoadServer fileUpLoadServer = new FileUpLoadServer(FinalVariables.SERVER_PORT);
fileUpLoadServer.load();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 3000);
}
}
Web.xml configuration (Follow project startup)
index.html
index.jsp
SocketServerListener
com.cn.csdn.seesun2012.socket.SocketServerListener
10
seesun2012
Currently supports MySQL,Oracle,SQL. Need to configure the database before using, can refer to me to write this article: blog.ncmem.com/wordpress/2…
Welcome to join the group to discuss: 374992201