java network programming for TCP communication and simple file upload function example

  • 2020-12-26 05:45:18
  • OfStack

TCP communication needs to be clear:

tcp communication is connection-oriented and requires that the server be started before the client.

Both the client and the server create socket objects, the client needs to 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 socket is a connected socket )
ServerSocket listen_socket = new ServerSocket(8888);  // Server socket, in this case a listening socket ( already bind() Address and port up )

The server needs to convert the listening socket to a connected socket using the accept() method. This listening socket can generate multiple connected sockets so that you can listen for requests from other clients when connected. Therefore, concurrent access should be implemented using multiple threads here. With the connected socket, you can get a lot of information about the client, such as the client's ip address, the port on which the request was sent, and so on.


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

To implement concurrent connections on the server side, the following code is generally used: ThreadTask is the threaded task object.


public static void main(String[] args) throws IOException {
 ServerSocket listen_sock = new ServerSocket(8888); // The listening socket needs only to be created 1 One, so outside of the mission 
 while (true) { // Each build 1 A connection, it's on 1 A thread 
  Socket conn_sock = listen_sock.accept(); // When there's no new connection, main The main thread is blocked here 
  new Thread(new ThreadTask(conn_sock)).start();
 }
}

The client needs to get the output stream based on the connected socket, and the server needs to get the input stream based on the socket. Of course, now that you have a connected socket, you can get either input stream or output stream.


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

The server should actively close the connected socket and the listening socket at the appropriate place.

The server should be continuously responsible for receiving in a loop.

Simple Client end:


import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
 public static void main(String[] args) {
 // 1. Create a client socket 
 Socket c_sock = null;
 OutputStream client_outstream = null;
 try {
  c_sock = new Socket("192.168.0.124",8888);
  // 2. Get output stream 
  client_outstream = c_sock.getOutputStream();
  // 3. The output data 
  client_outstream.write("Hello,i'm coming".getBytes());
 } catch (IOException e) {
  e.printStackTrace();
 } finally {
  if(c_sock != null){
  try{
   c_sock.close();
  } catch(IOException e) {
   e.printStackTrace();
  }
  }
 }
 }
}

Simple Server end:


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 listening socket 
 ServerSocket listen_sock = null;
 try {
  listen_sock = new ServerSocket(8888);
 } catch(IOException i) {
  i.printStackTrace();
 }
 Socket server_sock = null;
 InputStream in_sock = null;
 while (true) {
  try {
  // 2. Establish a connection with the client, generate a connected socket, and get the client ip address 
  server_sock = listen_sock.accept();
  String client_ip = server_sock.getInetAddress().getHostAddress();
  System.out.println("Client: " + client_ip + " connected");
  // 3. Gets the input stream and reads the data sent by the client based on the connected socket 
  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 is tcp's file upload function:

In addition to the output stream of the socket, the client has an input stream that reads the local file, and an input stream of the socket that reads the feedback from the server.

The server also has three streams: input and output streams for sockets, and output streams for writing to the uploaded target file.

After the client has read all the data from the local file, it needs to use the socket's shutdownOutput() to notify the server that the output stream of the socket has reached the end.

In order to provide upload function for multiple people, the server needs to use multi-thread to realize concurrent connection.

Client side:


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;
  FileInputStream local_read = null;
  try {
   // 1. Client socket 
   send_sock = new Socket(server_addr, server_port);
   // 2. Gets the output stream of the connection pipe 
   OutputStream send_stream = send_sock.getOutputStream();
   // 3. The byte input stream reads the local file data and sends it out using the output stream of the socket 
   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. The tag output streams to the end 
   send_sock.shutdownOutput();
   // 5. Receive feedback data from the server, such as successful upload, failed upload, etc 
   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 side:


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); // The listening socket needs only to be created 1 One, so outside of the mission 
  while (true) { // Each build 1 A connection, it's on 1 A thread 
   Socket conn_sock = listen_sock.accept(); // When there's no new connection, main The main thread is blocked here 
   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; //  Connect sockets 
 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. Gets the input stream for the connection pipe 
   recv_stream = conn_sock.getInputStream();
   //  The client ip
   String client_ip = conn_sock.getInetAddress().getHostAddress();
   System.out.println(client_ip + ".....connected");
   // 2. File upload location, that is, output target, to ip A name. If the file already exists, create a new file using parentheses and numbers, as in "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. Reads the data and writes 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.  Feedback information to the client 
   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();
    }
   }
  }
 }
}

Related articles: