Java uploads files to the server and client, and java uploads files

Source: Internet
Author: User

Java uploads files to the server and client, and java uploads files

Write a server and client that can upload files in JAVA. The specific content is as follows:

Server

Class Server {public static void main (String [] args) throws Exception {// create a Server Socket ServerSocket ss = new ServerSocket (10005); // receive client Socket fileLoaderSocket = ss. accept (); // print the connection information String ip = fileLoaderSocket. getInetAddress (). getHostAddress (); System. out. println (ip + "... conncected "); // receives the file and saves InputStream in = fileLoaderSocket. getInputStream (); // instantiate object fileSave OutputStream fileSave = New FileOutputStream ("E: \ 3.mp3"); // create an array buf byte [] buf = new byte [1024]; int len = 0; // determine whether to read the while (len = in. read (buf ))! =-1) {fileSave. write (buf, 0, len); // refresh fileSave. flush ();} // returns the file copy information BufferedWriter out = new BufferedWriter (new OutputStreamWriter (fileLoaderSocket. getOutputStream (); out. write ("File Uploaded successfully"); // refresh out. flush (); // resource close ss. close (); fileLoaderSocket. close (); fileSave. close ();}}

Client:

Class Client {public static void main (String [] args) throws Exception {// establish the Socket service Socket fileLoaderSocket = new Socket ("168.168.168.94", 10005 ); // read the file locally from the client and write it into the socket output stream OutputStream out = fileLoaderSocket. getOutputStream (); // instantiate object fileReader InputStream fileRead = new FileInputStream ("G: \ 2.mp3"); // create an array byte [] buf = new byte [1024]; int len = 0; // determine whether to read the while (len = fileRead. read (buf ))! =-1) {out. write (buf, 0, len);} // tells the server that the file has been transferred. fileLoaderSocket. shutdownOutput (); // get the feedback from the server. BufferedReader in = new BufferedReader (new InputStreamReader (fileLoaderSocket. getInputStream (); String serverBack = in. readLine (); System. out. println (serverBack); // closes fileLoaderSocket. close (); fileRead. close ();}}

The following procedures are directly copied from other places for your reference:

Java Socket programming

Java Socket programming involves two concepts: ServerSocket and Socket. The server and the client establish a connection through Socket, and then they can communicate. First, ServerSocket listens to a port on the server. When a Socket is found on the client to connect to it, it will access the connection request of the Socket, at the same time, establish a corresponding Socket on the server to communicate with it. In this way, there are two sockets, one for each client and one for the server.
The communication between sockets is actually very simple. When the server writes something into the Socket output stream, the client can read the corresponding content through the Socket input stream. The Socket and Socket are two-way connected, so the client can write something into the corresponding Socket output stream, and then the corresponding Socket input stream on the server can read the corresponding content. Here are some examples of communication between the server and the client:

1. The client writes data to the server.

Server Java code

Public class Server {public static void main (String args []) throws IOException {// For the sake of simplicity, all exception information is throttled with int port = 8899; // define a ServerSocket listener on port 8899 ServerSocket server = new ServerSocket (port); // server attempts to receive connection requests from other sockets, the accept method of server is blocking Socket socket = server. accept (); // After establishing a connection with the client, we can obtain the InputStream of the socket and read the information sent from the client. Reader reader = new InputStreamReader (socket. getInputStream (); char chars [] = new char [64]; int len; StringBuilder sb = new StringBuilder (); while (len = reader. read (chars ))! =-1) {sb. append (new String (chars, 0, len);} System. out. println ("from client:" + sb); reader. close (); socket. close (); server. close ();}}

The operation of the server to read data from the InputStream of the Socket is also blocking. If the data is not read from the input stream, it will remain there, until the client writes data to the Socket output stream or closes the Socket output stream. Of course, the same is true for the client Socket. After the operation, remember to close the corresponding resources before the entire program ends, that is, close the corresponding IO stream and Socket.

Client Java code

Public class Client {public static void main (String args []) throws Exception {// For simplicity, all exceptions are directly thrown out of String host = "127.0.0.1 "; // int port = 8899; // listening port corresponding to the server to be connected // establish a connection with the server Socket client = new Socket (host, port ); // after the connection is established, you can write data to the server. Writer writer = new OutputStreamWriter (client. getOutputStream (); writer. write ("Hello Server. "); writer. flush (); // remember flush writer after writing. close (); client. close ();}}

Note that the client writes data to the Socket output stream and transmits it to the server. If the program is not closed after the write operation, instead, perform other blocking operations (such as reading data from the input stream). Remember to flush the data so that the server can receive the data sent by the client, otherwise, the two sides may wait infinitely. This problem will be mentioned later when we talk about both the client and the server reading and writing at the same time.

2. Both the client and the server read and write data at the same time.

As mentioned above, sockets communicate in two directions, which can receive and send data.

Server Java code

Public class Server {public static void main (String args []) throws IOException {// For the sake of simplicity, all exception information is throttled with int port = 8899; // define a ServerSocket listener on port 8899 ServerSocket server = new ServerSocket (port); // server attempts to receive connection requests from other sockets, the accept method of server is blocking Socket socket = server. accept (); // After establishing a connection with the client, we can obtain the InputStream of the socket and read the information sent from the client. Reader reader = new InputStreamReader (socket. getInputStream (); char chars [] = new char [64]; int len; StringBuilder sb = new StringBuilder (); while (len = reader. read (chars ))! =-1) {sb. append (new String (chars, 0, len);} System. out. println ("from client:" + sb); // write a new OutputStreamWriter (socket. getOutputStream (); writer. write ("Hello Client. "); writer. flush (); writer. close (); reader. close (); socket. close (); server. close ();}}

In the above Code, we first read the data sent from the client from the input stream, then write data to the client in the output stream, and then close the corresponding resource file. In fact, the above Code may not run in the way we imagined in advance, because reading data from the input stream is a blocking operation, in the above while LOOP, when reading data, the loop body will be executed; otherwise, the loop body will be blocked, so that subsequent write operations will never be executed. The while loop will also jump out unless the corresponding Socket of the client is disabled. The solution to this situation that may never be executed is that the while loop needs to be jumped out with conditions in it. Looking at the above Code, in the ever-changing situation, only the length len and read data can be obtained. len is no longer usable. The only thing that can be used is the read data. In this case, we usually specify an end tag. When the data sent by the client contains an end tag, it indicates that the current data has been sent, at this time, we can jump out of the loop. The improved code will look like this:

Java code

Public class Server {public static void main (String args []) throws IOException {// For the sake of simplicity, all exception information is throttled with int port = 8899; // define a ServerSocket listener on port 8899 ServerSocket server = new ServerSocket (port); // server attempts to receive connection requests from other sockets, the accept method of server is blocking Socket socket = server. accept (); // After establishing a connection with the client, we can obtain the InputStream of the socket and read the information sent from the client. Reader reader = new InputStreamReader (socket. getInputStream (); char chars [] = new char [64]; int len; StringBuilder sb = new StringBuilder (); String temp; int index; while (len = reader. read (chars ))! =-1) {temp = new String (chars, 0, len); if (index = temp. indexOf ("eof "))! =-1) {// when eof is encountered, the receiving sb ends. append (temp. substring (0, index); break;} sb. append (temp);} System. out. println ("from client:" + sb); // write a new OutputStreamWriter (socket. getOutputStream (); writer. write ("Hello Client. "); writer. flush (); writer. close (); reader. close (); socket. close (); server. close ();}}

In the above Code, when the server reads the end mark sent by the client, that is, "eof", it ends receiving and terminating the data loop, so that subsequent code can continue.

Client Java code

Public class Client {public static void main (String args []) throws Exception {// For simplicity, all exceptions are directly thrown out of String host = "127.0.0.1 "; // int port = 8899; // listening port corresponding to the server to be connected // establish a connection with the server Socket client = new Socket (host, port ); // after the connection is established, you can write data to the server. Writer writer = new OutputStreamWriter (client. getOutputStream (); writer. write ("Hello Server. "); writer. flush (); // read the data after writing. Reader = new InputStrea MReader (client. getInputStream (); char chars [] = new char [64]; int len; StringBuffer sb = new StringBuffer (); while (len = reader. read (chars ))! =-1) {sb. append (new String (chars, 0, len);} System. out. println ("from server:" + sb); writer. close (); reader. close (); client. close ();}}

In the above Code, we first send a piece of data to the server, and then read the data returned by the server. The process of reading the data from the server may cause the program to be stuck there, never skip the while loop. This code, in combination with the server's first piece of code, allows us to analyze where the server will always receive data and never jump out of the while loop, so that no subsequent server will return data to the client, the client cannot receive the data returned by the server. The solution is shown in the second code of the server. After the client sends data, it writes the end mark to the output stream to tell the server that the data has been sent, after the server returns data, it also sends a tag to the client. The modified client code looks like this:

Java code

Public class Client {public static void main (String args []) throws Exception {// For simplicity, all exceptions are directly thrown out of String host = "127.0.0.1 "; // int port = 8899; // listening port corresponding to the server to be connected // establish a connection with the server Socket client = new Socket (host, port ); // after the connection is established, you can write data to the server. Writer writer = new OutputStreamWriter (client. getOutputStream (); writer. write ("Hello Server. "); writer. write ("eof"); writer. flush (); // read Reader re after writing Ader = new InputStreamReader (client. getInputStream (); char chars [] = new char [64]; int len; StringBuffer sb = new StringBuffer (); String temp; int index; while (len = reader. read (chars ))! =-1) {temp = new String (chars, 0, len); if (index = temp. indexOf ("eof "))! =-1) {sb. append (temp. substring (0, index); break;} sb. append (new String (chars, 0, len);} System. out. println ("from server:" + sb); writer. close (); reader. close (); client. close ();}}

In our daily use, the client sends data to the server, and the server receives the data before returning the corresponding results to the client. It's just that the relationship between the client and the server is no longer one-to-one, but the situation where multiple clients correspond to the same server as described below.

3. Multiple Clients connect to the same server

As in the previous two examples, the server end after receiving the request from a client and cannot receive the request from other clients. This often does not meet our requirements. We usually do this:

Java code

Public class Server {public static void main (String args []) throws IOException {// For the sake of simplicity, all exception information is throttled with int port = 8899; // define a ServerSocket listener on port 8899 ServerSocket server = new ServerSocket (port); while (true) {// server attempts to receive connection requests from other sockets, the accept method of server is blocking Socket socket = server. accept (); // After establishing a connection with the client, we can obtain the InputStream of the socket and read the information sent from the client. Reader reader = new InputStreamReader (socket. getInputStream (); char chars [] = new char [64]; int len; StringBuilder sb = new StringBuilder (); String temp; int index; while (len = reader. read (chars ))! =-1) {temp = new String (chars, 0, len); if (index = temp. indexOf ("eof "))! =-1) {// when eof is encountered, the receiving sb ends. append (temp. substring (0, index); break;} sb. append (temp);} System. out. println ("from client:" + sb); // write a new OutputStreamWriter (socket. getOutputStream (); writer. write ("Hello Client. "); writer. flush (); writer. close (); reader. close (); socket. close ();}}}

In the above Code, we use an endless loop. in the loop body, ServerSocket calls its accept method to try to receive connection requests from clients. When the request is not received, the program will block it here until it receives the connection request from the client and then communicates with the client that has established the connection, after completion, the loop body is executed to receive new connection requests again. In this way, our ServerSocket can receive connection requests from all clients and communicate with them. This achieves a simple mode for a server to communicate with multiple clients.
In the preceding example, a server can communicate with multiple clients, but there is still a problem. In the preceding example, the server processes client connection requests synchronously. After receiving a connection request from the client, you must first communicate with the current client before processing the next connection request. This will seriously affect the program performance when the concurrency is large. For this reason, we can change it to the following asynchronous Processing Method for communication with the client:

Java code

Public class Server {public static void main (String args []) throws IOException {// For the sake of simplicity, all exception information is throttled with int port = 8899; // define a ServerSocket listener on port 8899 ServerSocket server = new ServerSocket (port); while (true) {// server attempts to receive connection requests from other sockets, the accept method of server is blocking Socket socket = server. accept (); // each time a Socket is received, a new Thread is created to process it. new Thread (new Task (socket )). start () ;}}/*** the */static class Task used to process Socket requests Implements Runnable {private Socket socket; public Task (Socket socket) {this. socket = socket;} public void run () {try {handleSocket ();} catch (Exception e) {e. printStackTrace () ;}}/*** communicates with the client Socket * @ throws Exception */private void handleSocket () throws Exception {Reader reader = new InputStreamReader (socket. getInputStream (); char chars [] = new char [64]; int len; StringBuilder sb = New StringBuilder (); String temp; int index; while (len = reader. read (chars ))! =-1) {temp = new String (chars, 0, len); if (index = temp. indexOf ("eof "))! =-1) {// when eof is encountered, the receiving sb ends. append (temp. substring (0, index); break;} sb. append (temp);} System. out. println ("from client:" + sb); // write a new OutputStreamWriter (socket. getOutputStream (); writer. write ("Hello Client. "); writer. flush (); writer. close (); reader. close (); socket. close ();}}}

In the code above, each time ServerSocket receives a new Socket connection request, a new thread will be started to communicate with the current Socket, in this way, the communication between asynchronous processing and client Socket is achieved.
When receiving data from the InputStream of the Socket, it is too complicated to read a little bit like above. Sometimes we will use BufferedReader to read a row at a time, for example:

Java code

Public class Server {public static void main (String args []) throws IOException {// For the sake of simplicity, all exception information is throttled with int port = 8899; // define a ServerSocket listener on port 8899 ServerSocket server = new ServerSocket (port); while (true) {// server attempts to receive connection requests from other sockets, the accept method of server is blocking Socket socket = server. accept (); // each time a Socket is received, a new Thread is created to process it. new Thread (new Task (socket )). start () ;}}/*** the */static class Task used to process Socket requests Implements Runnable {private Socket socket; public Task (Socket socket) {this. socket = socket;} public void run () {try {handleSocket ();} catch (Exception e) {e. printStackTrace () ;}}/*** communicates with the client Socket * @ throws Exception */private void handleSocket () throws Exception {BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputStream (); StringBuilder sb = new StringBui Lder (); String temp; int index; while (temp = br. readLine ())! = Null) {System. out. println (temp); if (index = temp. indexOf ("eof "))! =-1) {// when eof is encountered, the receiving sb ends. append (temp. substring (0, index); break;} sb. append (temp);} System. out. println ("from client:" + sb); // write a new OutputStreamWriter (socket. getOutputStream (); writer. write ("Hello Client. "); writer. write ("eof \ n"); writer. flush (); writer. close (); br. close (); socket. close ();}}}

At this time, it should be noted that the readLine method of BufferedReader reads a row at a time. This method is blocked until it reads a row of data and the program continues to execute, so when will readLine read a row? It is not until the program encounters a line break or the readLine method of the response stream that it considers to have read a row that will end the blocking, so that the program continues to execute. Therefore, when reading data using the readLine of BufferedReader, remember to write a line break in the corresponding output stream (after the stream ends, it is automatically marked as end, And readLine can be recognized ), after writing line breaks, remember to flush the output stream if it is not immediately closed, so that the data can be truly written from the buffer. Corresponding to the above Code, our client program should be written as follows:

Java code

Public class Client {public static void main (String args []) throws Exception {// For simplicity, all exceptions are directly thrown out of String host = "127.0.0.1 "; // int port = 8899; // listening port corresponding to the server to be connected // establish a connection with the server Socket client = new Socket (host, port ); // after the connection is established, you can write data to the server. Writer writer = new OutputStreamWriter (client. getOutputStream (); writer. write ("Hello Server. "); writer. write ("eof \ n"); writer. flush (); // read Buffere after writing DReader br = new BufferedReader (new InputStreamReader (client. getInputStream (); StringBuffer sb = new StringBuffer (); String temp; int index; while (temp = br. readLine ())! = Null) {if (index = temp. indexOf ("eof "))! =-1) {sb. append (temp. substring (0, index); break;} sb. append (temp);} System. out. println ("from server:" + sb); writer. close (); br. close (); client. close ();}}

4. Set the timeout time

If there is such a requirement, our client needs to obtain XX information from the server through Socket, and then display it to the user on the page. We know that the Socket is blocked when reading data. If you do not read the data, the program will be blocked all the time. When synchronizing requests, we certainly cannot allow such a situation. This requires us to control the blocking interruption after the request reaches a certain time, so that the program can continue to run. Socket provides us with a setSoTimeout () method to set the timeout time for receiving data, in milliseconds. When the set timeout time is greater than 0 and the Socket has not received the returned data after this time, the Socket will throw a SocketTimeoutException.
Suppose we need to control our client to interrupt the blocking operation after 10 seconds of reading data. We can do this:

Java code

Public class Client {public static void main (String args []) throws Exception {// For simplicity, all exceptions are directly thrown out of String host = "127.0.0.1 "; // int port = 8899; // listening port corresponding to the server to be connected // establish a connection with the server Socket client = new Socket (host, port ); // after the connection is established, you can write data to the server. Writer writer = new OutputStreamWriter (client. getOutputStream (); writer. write ("Hello Server. "); writer. write ("eof \ n"); writer. flush (); // read Buffere after writing DReader br = new BufferedReader (new InputStreamReader (client. getInputStream (); // sets the supertime to 10 seconds. setSoTimeout (10*1000); StringBuffer sb = new StringBuffer (); String temp; int index; try {while (temp = br. readLine ())! = Null) {if (index = temp. indexOf ("eof "))! =-1) {sb. append (temp. substring (0, index); break;} sb. append (temp) ;}} catch (SocketTimeoutException e) {System. out. println ("data read timeout. ");} System. out. println (" from server: "+ sb); writer. close (); br. close (); client. close ();}}

5. garbled receiving data

In this case, the server or client receives Chinese garbled characters because the encoding used for data transmission is inconsistent with the encoding used for receiving. For example, there is the following server code:

Java code

Public class Server {public static void main (String args []) throws IOException {// For the sake of simplicity, all exception information is throttled with int port = 8899; // define a ServerSocket listener on port 8899 ServerSocket server = new ServerSocket (port); while (true) {// server attempts to receive connection requests from other sockets, the accept method of server is blocking Socket socket = server. accept (); // each time a Socket is received, a new Thread is created to process it. new Thread (new Task (socket )). start () ;}}/*** the */static class Task used to process Socket requests Implements Runnable {private Socket socket; public Task (Socket socket) {this. socket = socket;} public void run () {try {handleSocket ();} catch (Exception e) {e. printStackTrace () ;}}/*** communicates with the client Socket * @ throws Exception */private void handleSocket () throws Exception {BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputStream (), "GBK"); StringBuilder sb = new St RingBuilder (); String temp; int index; while (temp = br. readLine ())! = Null) {System. out. println (temp); if (index = temp. indexOf ("eof "))! =-1) {// when eof is encountered, the receiving sb ends. append (temp. substring (0, index); break;} sb. append (temp);} System. out. println ("client:" + sb); // after reading it, write a Writer writer = new OutputStreamWriter (socket. getOutputStream (), "UTF-8"); writer. write ("Hello, client. "); Writer. write ("eof \ n"); writer. flush (); writer. close (); br. close (); socket. close ();}}}

This is a bit confusing for testing. In the above server code, we clearly defined the use of GBK encoding to read data when defining the input stream, while explicitly specifying the use of UTF-8 encoding to send data when defining the output stream. If the client does not send data in GBK encoding, the data received by the server may be garbled. Similarly, if the client does not send data in encoding, that is to say, if the UTF-8 code is used to receive data, it is very likely that there will be data garbled. Therefore, for the above server code, in order for our program to read the data sent by the other party without garbled code, our client should be like this:

Java code

Public class Client {public static void main (String args []) throws Exception {// For simplicity, all exceptions are directly thrown out of String host = "127.0.0.1 "; // int port = 8899; // listening port corresponding to the server to be connected // establish a connection with the server Socket client = new Socket (host, port ); // after the connection is established, you can write data to the server. Writer writer = new OutputStreamWriter (client. getOutputStream (), "GBK"); writer. write ("Hello, server. "); Writer. write ("eof \ n"); writer. flush (); // read BufferedReader after writing; br = new BufferedReader (new InputStreamReader (client. getInputStream (), "UTF-8"); // sets the supertime to 10 seconds client. setSoTimeout (10*1000); StringBuffer sb = new StringBuffer (); String temp; int index; try {while (temp = br. readLine ())! = Null) {if (index = temp. indexOf ("eof "))! =-1) {sb. append (temp. substring (0, index); break;} sb. append (temp) ;}} catch (SocketTimeoutException e) {System. out. println ("data read timeout. ");} System. out. println (" server: "+ sb); writer. close (); br. close (); client. close ();}}

This article has been compiled into Java upload operation tips summary. You are welcome to learn and read this article.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.