Java Network Programming-TCP communication and simple file upload function instance, tcp File Upload

Source: Internet
Author: User

Java Network Programming-TCP communication and simple file upload function instance, tcp File Upload

TCP communication needs to be clarified:

Tcp communication is connection-oriented. You need to start the server and then the client.

Both the client and the server must create a socket object. The client must specify the server socket (ip + port), and the server must specify the service port.

Socket client_socket = new Socket ("192.168.100.17", 8888); // client Socket (Socket class: connected Socket) ServerSocket listen_socket = new ServerSocket (8888 ); // server socket, which is the listening socket (already bind () address and port)

The server must use the accept () method to change the listening socket to a connected socket. This listening socket can generate multiple connected sockets, so that after the connection, it can also listen to requests from other clients. Therefore, multithreading should be used for concurrent access. After obtaining the connected socket, you can obtain a lot of client information, such as the IP address of the client and the port on which the request is sent.

Socket server_scoket = socket.accept();Socket server_scoket2 = socket.accept();Socket server_scoket3 = socket.accept();

To implement concurrent connections, the server uses the following code: ThreadTask is a thread task object.

Public static void main (String [] args) throws IOException {ServerSocket listen_sock = new ServerSocket (8888); // only one listener socket needs to be created, so while (true) outside the task) {// each time a connection is established, a thread Socket conn_sock = listen_sock.accept () is enabled; // when no new connection comes in, the main Thread is blocked in this new Thread (new ThreadTask (conn_sock )). start ();}}

The client needs to obtain the output stream based on the connected socket. The server needs to obtain the input stream based on the socket. Of course, since a socket is connected, the input stream and output stream can be obtained at any end.

OutputStream send_stream = client_socket.getOutputStream (); // The client obtains the output stream InputStream recv_stream = server_socket.getInputStream ();

The server should take the initiative to close connected sockets, and close the listening socket in a proper place.

The server should receive messages cyclically.

Simple Client:

Import java. io. IOException; import java. io. outputStream; import java.net. socket; public class TCPClient {public static void main (String [] args) {// 1. create client Socket c_sock = null; OutputStream client_outstream = null; try {c_sock = new Socket ("192.168.0.124", 8888); // 2. obtain the output stream client_outstream = c_sock.getOutputStream (); // 3. output Data client_outstream.write ("Hello, I'm coming ". getBytes ();} catch (IOEx Ception e) {e. printStackTrace ();} finally {if (c_sock! = Null) {try {c_sock.close ();} catch (IOException e) {e. printStackTrace ();}}}}}

Simple Server:

Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java.net. serverSocket; import java.net. socket; public class TCPServer {public static void main (String [] args) {// 1. create a listener socket ServerSocket listen_sock = null; try {listen_sock = new ServerSocket (8888);} catch (IOException I) {I. printStackTrace ();} Socket server_sock = null; I NputStream in_sock = null; while (true) {try {// 2. establish a connection with the client, generate a connected socket, and obtain the Client IP address server_sock = listen_sock.accept (); String client_ip = server_sock.getInetAddress (). getHostAddress (); System. out. println ("Client:" + client_ip + "connected"); // 3. obtain the input stream based on the connected socket and read the data in_sock = server_sock.getInputStream (); BufferedReader bufr = new BufferedReader (new InputStreamReader (in_sock); String line = Null; while (line = bufr. readLine ())! = Null) {System. out. println (line);} // 4. close the connected socket server_sock.close ();} catch (IOException e) {e. printStackTrace ();}}}}

The following describes how to upload a file over tcp:

In addition to the socket output stream, the client also reads the input stream of the local file, and the socket input stream to read the feedback from the server.

The server also has three streams: Socket input and output streams, which are written into the output stream of the uploaded target file.

After the client reads all the data in the local file, it needs to use the socket shutdownOutput () to notify the server socket that the output stream has reached the end.

To provide the upload function for multiple users, the server must use multiple threads for concurrent connections.

Client:

Import java. io. bufferedReader; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java.net. socket; public class UploadClient {public static void main (String [] args) {// TODO Auto-generated method stub String server_addr = "192.168.0.124"; int server_port = 8888; socket send_sock = null; FileInputSt Ream local_read = null; try {// 1. client Socket send_sock = new Socket (server_addr, server_port); // 2. obtain the output stream OutputStream send_stream = send_sock.getOutputStream (); // 3. the Byte input stream reads local file data and uses the socket output stream to send it out local_read = new FileInputStream ("d:/myjava/net/SQL .docx "); byte [] buf = new byte [1024]; int len = 0; while (len = local_read.read (buf ))! =-1) {send_stream.write (buf, 0, len);} // 4. mark the output stream to send_sock.shutdownOutput (); // 5. receives feedback from the server, for example, InputStream recv_stream = send_sock.getInputStream (); BufferedReader ack_recv = new BufferedReader (new InputStreamReader (recv_stream); String line = null; while (line = ack_recv.readLine ())! = Null) {System. out. println (line) ;}} catch (IOException I) {I. printStackTrace () ;}finally {if (send_sock! = Null) {try {send_sock.close (); local_read.close ();} catch (IOException i1) {i1.printStackTrace () ;}} if (local_read! = Null) {try {local_read.close ();} catch (IOException i2) {i2.printStackTrace ();}}}}}

Server:

Import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import java.net. serverSocket; import java.net. socket; public class UploadServer {public static void main (String [] args) throws IOException {ServerSocket listen_sock = new ServerSocket (8888); // you only need to create one listening Socket, therefore, when a connection is established outside the task while (true) {// each time a connection is established, a thread Socket conn_sock = li is enabled. Sten_sock.accept (); // when there is no new connection, the main Thread is blocked in this new Thread (new Uploader (conn_sock )). start () ;}} class Uploader implements Runnable {private File dest_dir = new File ("d:/temp"); // upload directory private Socket conn_sock = null; // connection Socket InputStream recv_stream = null; FileOutputStream dest_stream = null; Uploader (Socket conn_sock) throws IOException {this. conn_sock = conn_sock;} public void run () {try {if (! Dest_dir.exists () {dest_dir.mkdirs ();} // 1. obtain the input stream recv_stream = conn_sock.getInputStream (); // Client ip String client_ip = conn_sock.getInetAddress (). getHostAddress (); System. out. println (client_ip + "..... connected "); // 2. file upload location, that is, the output target, named by ip. If the File already exists, use parentheses and numbers to create a new File, for example, "192.168.100.23(1).txt" File dest_file = new File (dest_dir, client_ip + ". docx "); int count = 1; while (dest_file.exists () {dest_file = new File (dest_dir, client_ip +" ("+ count +") "+ ". docx "); count ++;} // 3. read data and write it to the target file dest_stream = new FileOutputStream (dest_file); byte [] buf = new byte [1024]; int len = 0; while (len = recv_stream.read (buf ))! =-1) {dest_stream.write (buf, 0, len);} // 4. Report OutputStream ack_send = conn_sock.getOutputStream (); byte [] text = "upload successful! ". GetBytes (); ack_send.write (text);} catch (IOException e1) {e1.printStackTrace () ;}finally {if (dest_stream! = Null) {try {dest_stream.close ();} catch (IOException I) {I. printStackTrace () ;}} if (conn_sock! = Null) {try {conn_sock.close ();} catch (IOException I) {I. printStackTrace ();}}}}}

The above java Network programming example of TCP communication and simple file upload function is all the content shared by xiaobian. I hope to give you a reference, and I hope you can provide more support to the customer's house.

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.