Java implements file upload server and client
- 2020-12-21 18:02:46
- OfStack
This article shares the Java implementation file upload server and client specific code for your reference, the specific content is as follows
File upload server:
/**
* use TCP The protocol realizes the upload function on the server side
* Ideas:
* new ServerSocket
* Wait for the client to connect
* After connecting to open the child thread, get the connection Socket To child threads
* Cycle are
* @author yajun
*
*/
public class UploadServer {
public static void main(String[] args) {
UploadServer server=new UploadServer();
UploadThread command=new UploadThread();
server.start(command);
}
/**
* Functions: Accept connection, open child thread, loop
* @param command The child thread object used for the download, which is implemented Runnable interface
*/
private void start(UploadThread command){
// A local variable
ServerSocket serverSocket = null;
Socket transSocket;
// The business logic
try {
serverSocket=new ServerSocket(55555);
while(true){
System.out.println(" Waiting to connect... ");
transSocket=serverSocket.accept();
int i=0;
i++;
System.out.println(" The first "+i+" A connection ");
// Do you want to close the thread after downloading??
command.setSocket(transSocket);
Executors.newFixedThreadPool(5).execute(command);
}
// Exception handling
} catch (IOException e) {
e.printStackTrace();
// Close the resource
} finally{
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}//End of try
}//End of connect
@Test
public void testConnect() {
// Test task: Run the server first, then run the client several times, the server segment can continuously create child threads, then the test is successful
// Test preparation: Construction 1 Three threads to simulate the download thread
UploadThread command=new UploadThread();
start(command);
}
@Test
public void testDown() throws IOException {
byte[] buf;
ByteArrayInputStream bis;
String str="canglaoshi.avi\ncontent,content,content";
buf=str.getBytes();
bis=new ByteArrayInputStream(buf);
UploadThread ut=new UploadThread();
ut.down(bis);
}
}
// Child threads that complete the various transport tasks
class UploadThread implements Runnable{
Socket socket;
public UploadThread(){}
public UploadThread(Socket socket){
this.socket=socket;
}
@Override
public void run() {
InputStream in;
try {
in = socket.getInputStream();
down(in);
// Exception handling
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// The test code
/*try {
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+", Replication is completed ");
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}//End of run
public void setSocket(Socket socket){
this.socket=socket;
}
// Download method
/**
* The goal: InputStream Writes the data to the local
* Ideas:
* 1. Get input stream , It is better to pass in the input stream rather than directly from Socket There are utilization unit tests
* 2. Read the file name from the input stream
* 3. Create a new file and file output stream
* 4. Read the file contents from the input stream to the file output stream
* 5.
* @throws IOException
*/
public void down(InputStream in) throws IOException{
// A local variable
char ch;
char[] nameArr=new char[256];
byte[] buf=new byte[1024];
String name="";
OutputStream out = null;
// The business logic
try {
// The first 1 Step: Get the file name and construct the file output stream
int i=0;
while((ch=(char) in.read())!='\n'){
nameArr[i++]= ch;
}
//name=nameArr.toString();// This sentence cannot convert an array of characters to a string. You need the following statement
name=new String(nameArr);
System.out.println(" The files to download are: "+name);
out=new FileOutputStream("src\\down\\"+name);
// The first 2 Step: Writes the rest of the input stream to a file
int len;
while((len=in.read(buf))!=-1){
out.write(buf,0,len);
}
out.flush();
// Exception handling
} catch (IOException e) {
e.printStackTrace();
// Close the resource
}finally{
// Question: can two captures be placed in 1 What about blocks? What's the best way to handle exceptions when a stream is closed?
in.close();
out.close();
}
// debugging
System.out.println(name);
}
}//End of UploadThread
File upload client:
/**
* use TCP Protocol to achieve the upload function of the client
* @author yajun
*/
public class UploadClient {
public static void main(String[] args) {
UploadClient client=new UploadClient();
client.upload("src\\thursday\\AsListTest.java");
}
/**
* Effect: Upload file to server
* 1. Establish a connection to the server
* 2. Get output stream
* 3. Writes the file contents to the output stream
* 4. Gets the response from the server
*/
private void upload(String name){
Socket socket=null;
OutputStream out;
try {
socket=new Socket("127.0.0.1", 55555);
out=socket.getOutputStream();
write2OutputStream(name, out);
// Exception handling
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testUpload() {
upload("src\\status.xml");
}
/**
* Effect: Writes the file to the output stream by passing in the file name and output stream
* @param path
* @throws IOException
*/
private void write2OutputStream(String path,OutputStream out) throws IOException{
FileInputStream fis = null;
byte[] buf=new byte[1024];
String fileName="";
// The business logic
try {
//1. Write file name
fileName=path.substring(path.lastIndexOf('\\')+1);
System.out.println(" The file name you want to upload is: "+fileName);
out.write(fileName.getBytes());
out.write('\n');
//2. Write file contents
fis=new FileInputStream(path);
int len;
while((len=fis.read(buf))!=-1){
out.write(buf, 0, len);
}
out.flush();
// Exception handling
} catch (IOException e) {
e.printStackTrace();
// Close the resource
} finally{
fis.close();
out.close();
}
}//End of upload
@Test
public void testWrite2OutputStream() throws IOException {
ByteArrayOutputStream out = null;
try {
out=new ByteArrayOutputStream();
write2OutputStream("src\\status.xml", out);
System.out.println(out.toString("utf-8"));
} catch (IOException e) {
e.printStackTrace();
} finally{
out.close();
}
}
}
This article has been collected in Java Upload operation Skills Summary, welcome to learn to read.