Introduction to Java Network Programming

Java Network Programming

1. Overview

  • computer network

    It refers to a computer system that connects multiple computers with independent functions in different geographical locations and their external equipment through communication lines and realizes resource sharing and information transmission under the management and coordination of network operating system, network pipeline software and network communication protocol.

  • Network programming

    It means that data can be exchanged between programs running on different computers to realize network interconnection.

2. Three Elements of Network Programming

IP

  • Unique identity of each device in the network
  • Each network terminal has a separate address in the network, which we use to transmit data in the network.
  • ipconfig: View local IP
  • ping: Test connection
  • Local loop address: 127.0.0.1

Port number

  • Unique identification of each program on the device
  • Every network program needs to bind a port number. When transferring data, besides determining which machine to send to, it also needs to specify which program to send to.
  • Port number range 0-65535
  • Writing network applications requires binding a port number, trying to use more than 1024, which is basically occupied by system programs.

Agreement

  • UDP

    Connectionless, data insecurity, fast speed, no distinction between client and server

  • TCP

    Connection-oriented (three handshakes), data security, slightly slow, divided into client and server

    Three handshakes: the client first initiates the request to the server, the server responds to the request, and transmits the data.

3. Network Programming (UDP Transport)

Sender

public class Demo_Send {

	public static void main(String[] args) throws IOException {
		DatagramSocket socket = new DatagramSocket();  //Creating a socket is equivalent to creating a wharf.
		String str = "what are you doing now?";
		DatagramPacket packet = // Creating packet s is equivalent to containers
				new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
		socket.send(packet);
		socket.close();
	}

}

Receiver

public class Demo_Receive {

	public static void main(String[] args) throws Exception {
		DatagramSocket socket = new DatagramSocket(6666);//Creating a socket is equivalent to creating a wharf.
		DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);//Equivalent to creating containers
		socket.receive(packet);
		
		byte[] arr = packet.getData();
		int len = packet.getLength();//Get the number of valid bytes
		System.out.println(new String(arr,0,len));
		socket.close();
	}

}

Run Demo_Receive first, then Demo_Send under the dos command window

4.UDP Transmission Optimization

Implementing Input Sending

Sender

public class Demo2_Send {

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in); //Create keyboard entry objects
		DatagramSocket socket = new DatagramSocket();  //Creating a socket is equivalent to creating a wharf.
		while(true){
			String line = sc.nextLine(); //Gets the string entered by the keyboard
			if("quit".equals(line)){
				break;
			}
			DatagramPacket packet = // Creating packet s is equivalent to containers
					new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
			socket.send(packet);
		}
		socket.close();
	}

}

Receiver

public class Demo2_Receive {

	public static void main(String[] args) throws Exception {
		DatagramSocket socket = new DatagramSocket(6666);//Creating a socket is equivalent to creating a wharf.
		DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);//Equivalent to creating containers
		while(true){
			socket.receive(packet);
			
			byte[] arr = packet.getData();
			int len = packet.getLength();//Get the number of valid bytes
			String ip = packet.getAddress().getHostAddress(); //Get IP address
			int port = packet.getPort(); //Get the port number
			System.out.println(ip+":"+port+":"+new String(arr,0,len));
		}
	}

}

5.UDP Transfer Multithreading

public class Demo_MoreThread {

	public static void main(String[] args) {
		new Receive().start();
		new Send().start();
	}

}

class Receive extends Thread{
	public void run(){
		try{
			DatagramSocket socket = new DatagramSocket(6666);//Creating a socket is equivalent to creating a wharf.
			DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);//Equivalent to creating containers
			while(true){
				socket.receive(packet);
				
				byte[] arr = packet.getData();
				int len = packet.getLength();//Get the number of valid bytes
				String ip = packet.getAddress().getHostAddress(); //Get IP address
				int port = packet.getPort(); //Get the port number
				System.out.println(ip+":"+port+":"+new String(arr,0,len));
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}

class Send extends Thread{
	public void run(){
		try{
			Scanner sc = new Scanner(System.in); //Create keyboard entry objects
			DatagramSocket socket = new DatagramSocket();  //Creating a socket is equivalent to creating a wharf.
			while(true){
				String line = sc.nextLine(); //Gets the string entered by the keyboard
				if("quit".equals(line)){
					break;
				}
				DatagramPacket packet = // Creating packet s is equivalent to containers
						new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
				socket.send(packet);
			}
			socket.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}

6. TCP Protocol

1. Client

  • Create socket connection server (specify IP address, port number) and find the corresponding server through IP address
  • Call socket's getInputStream() and getOutputStream() methods to get IO flows connected to the client
  • The input stream can read the data written by the output stream of the server.
  • The output stream can write the input stream from the data to the server.

2. Server

  • Create ServerSocket (need to specify port number)
  • The accept calling ServerSocket receives a request from the client and gets a socket.
  • The input stream can read the data written by the client output stream.
  • The output stream can write the input stream of data to the client.

Client

public class Demo_Client {

	public static void main(String[] args) throws Exception, IOException {
		Socket socket = new Socket("127.0.0.1",12345);
		InputStream is = socket.getInputStream(); //Get the client's input stream
		OutputStream os = socket.getOutputStream();// Get the client's output stream
		
		byte[] arr = new byte[1024];
		int len = is.read(arr);
		System.out.println(new String(arr,0,len));
		
		os.write("Study hard and make progress every day".getBytes());
		
		socket.close();;
	}

}

Server

public class Demo_Server {

	public static void main(String[] args) throws Exception {
		ServerSocket server = new ServerSocket(12345);
		
		Socket socket =  server.accept();//Receiving client requests
		InputStream is = socket.getInputStream();
		OutputStream os = socket.getOutputStream();
		
		os.write("Baidu, you know".getBytes());
		
		byte[] arr = new byte[1024];
		int len = is.read(arr);
		System.out.println(new String(arr,0,len));
		
		socket.close();
		
	}

}

In dos command window, first run the server, then run the client

7. TCP protocol code optimization

Client

public class Demo2_Client {

	public static void main(String[] args) throws Exception, IOException {
		Socket socket = new Socket("127.0.0.1",12345);
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //Get the client's input stream
		PrintStream ps  = new PrintStream(socket.getOutputStream());// Get the client's output stream
		System.out.println(br.readLine());
		ps.println("Welcome to Xiyou Post");
		
		
		socket.close();;
	}

}

Server

public class Demo2_Client {

	public static void main(String[] args) throws Exception, IOException {
		Socket socket = new Socket("127.0.0.1",12345);
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //Get the client's input stream
		PrintStream ps  = new PrintStream(socket.getOutputStream());// Get the client's output stream
		System.out.println(br.readLine());
		ps.println("Welcome to Xiyou Post");
		
		
		socket.close();;
	}

}

8.TCP Server Multithreading

public class Demo2_Server {

	public static void main(String[] args) throws Exception {
		ServerSocket server = new ServerSocket(12345);
		while(true){
			final Socket socket =  server.accept();//Receiving client requests
			new Thread(){
				public void run(){
					try {
						BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //Get the client's input stream
						PrintStream ps  = new PrintStream(socket.getOutputStream());// Get the client's output stream
						ps.println("3g Laboratory");
						System.out.println(br.readLine());
						
						socket.close();
					} catch (IOException e) {
						
						e.printStackTrace();
					}
				}
			}.start();
			
		}
		
	}

}


9. Exercise

The client writes the string to the server (keyboard input), the server (multi-threaded) writes the string back after inversion, and the client reads the inverted string again.

Client

public class Test1_Client {

	public static void main(String[] args) throws Exception, IOException {
		Scanner sc = new Scanner(System.in);
		Socket socket = new Socket("127.0.0.1",12345);
		
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintStream ps = new PrintStream(socket.getOutputStream());
		
		ps.println(sc.nextLine());
		
		System.out.println(br.readLine());
		
		socket.close();
		
	}

}

Server

public class Test1_Server {
	
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(12345);
		System.out.println("Server startup, binding port 12345.");
		
		while(true){
			final Socket socket = server.accept();// Open a thread when receiving a client request
			new Thread(){
				public void run(){
					try {
						BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
						PrintStream ps = new PrintStream(socket.getOutputStream());
																				
						String line = br.readLine();
						line = new StringBuilder(line).reverse().toString();
						ps.println(line);
						socket.close();
					} catch (IOException e) {
						
						e.printStackTrace();
					}
				}
			}.start();
		}
		
	}

}

10. Practice

Client uploads files to server

step

Client

1. Enter the file path to upload to verify the existence of the path and whether it is a folder.

2. Send file name to server

Server

3. Establishing a multithreaded server

4. Read file names

5. Determine whether the file exists and send the result back to the client

6. Accept the result and quit if prompted

7. If it does not exist, define FileInputStream to read files and write them to the network

Server

8. Define FileOutputStream to read data from the network and store it locally

Client

public class Test_UpdateClient {

	public static void main(String[] args) throws Exception, IOException {
		File file = getFile();
		
		Socket socket = new Socket("127.0.0.1",12345);
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintStream ps = new PrintStream(socket.getOutputStream());
		
		ps.println(file.getName());
		
		String result =br.readLine();//Read if there is a result
		if("existence".equals(result)){
			System.out.println("The file you uploaded already exists, please do not upload it again!");
			socket.close();
			return;
		}else{
			FileInputStream fis = new FileInputStream(file);
			byte[] arr = new byte[8192];
			int len;
			while((len = fis.read(arr))!=-1){
				ps.write(arr,0,len);
			}
			System.out.println("Document upload success!!");
			fis.close();
			socket.close();
		}
	}

	private static File getFile() {
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a file path:");
		
		while(true){
			String line = sc.nextLine();
			File file = new File(line);
			
			if(!file.exists()){
				System.out.println("The file path you entered does not exist. Please re-enter:");
			}else if(file.isDirectory()){
				System.out.println("You entered a folder path, please enter a file path:");
			}else{
				return file;
			}
		}
	}

}

Server

public class Test_UpdateServer {

	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(12345);
		System.out.println("The server starts and binds port number 12345.");
		while(true){
			final Socket socket = server.accept();
			new Thread(){
				public void run(){
					try {
						InputStream is = socket.getInputStream();
						BufferedReader br = new BufferedReader(new InputStreamReader(is));
						PrintStream ps = new PrintStream(socket.getOutputStream());
						String fileName = br.readLine();
						
						File dir = new File("update");
						dir.mkdir(); //create folder
						File file = new File(dir,fileName);//Encapsulating file objects
						
						if(file.exists()){//If the server already has this file, it will exist and write to the client
							ps.println("Existence.");
							socket.close();
						}else{
							ps.println("Non-existent.");
							FileOutputStream fos = new FileOutputStream(file);
							byte[] arr = new byte[8192];
							int len;
							while((len = is.read(arr))!=-1){
								fos.write(arr,0,len);
							}
							fos.close();
							socket.close();
							server.close();
						}
						
						
					} catch (IOException e) {
						
						e.printStackTrace();
					}
				}
			}.start();
		}
	}

}

Keywords: socket network Programming Java

Added by pirri on Mon, 05 Aug 2019 10:00:32 +0300