JAVA Network Programming and Classical Case Echo

Keywords: socket Java network jvm

Java's network concept is not distinguished by the host, but by the process. JVM helps to solve the network transmission without our consideration.
Although JVM helps users hide the original information of the network, some operations are left to users. There are two kinds of network connections: TCP (reliable data connection) and UDP (unreliable data connection).
In terms of the essence of network programming, there are also two kinds of structures:
1. C/S structure (client and server): two kinds of programs need to be developed, one set of server programs and one set of client programs. If you want to update, two sets of programs need to be developed. The development is complex and high, but safe and stable, because you can customize the protocol and the transmission port.
2. B/S structure (browser/server): To access server-side programs through browsers, developers only need to develop server-side code, only need to maintain a set of server programs, because the use of public protocols. Open ports, so security is poor.

Server-side code:

public class HelloServer {

	public static void main(String[] args) throws Exception {
		//1. Create a server object. Each server object must have a listening port.
		ServerSocket server=new ServerSocket(9999);//At this point, the service is on 9999, waiting for connection
		System.out.println("Waiting for Customer Connection............");
		//2. We need to wait for the client to connect, that is to say, the program will enter a blocking state here.
		Socket clietn=server.accept();//Waiting for a connection, all connected are customers, and each customer is represented by Scoket
		PrintWriter out=new PrintWriter(clietn.getOutputStream());
		out.println("Hello World");
		out.close();
		server.close();
		
	}
}

Client code:

import java.net.Socket;
import java.util.Scanner;

public class HelloClent {
	@SuppressWarnings("resource")
	public static void main(String[] args) throws Exception {
		//Represents the host name and port of the specified server side of the connection
		Socket client=new Socket("localhost",9999);
		Scanner sc=new Scanner(client.getInputStream());
		sc.useDelimiter("\n");
		while(sc.hasNext()){
			System.out.println(sc.next());
		}
		
		client.close();
	}
}

Classic case: Echo

Realization of a Server with Multiple Hosts by Multithreading

Server side:

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServer {
	public static void main(String[] args) throws Exception {
		ServerSocket server = new ServerSocket(8888);
		boolean flag=true;
		while(flag){
			Socket client = server.accept(); // Waiting for program connection
			new Thread(new MyThread(client)).start();;
		}
		server.close();
	}

	private static class MyThread implements Runnable {
		private Socket client;
		
		public MyThread(Socket client) {
			super();
			this.client = client;
		}

		@Override
		public void run() {
			try {
				Scanner sc = new Scanner(client.getInputStream()); // Receiving client data
				PrintStream out = new PrintStream(client.getOutputStream()); // Response information to client
				sc.useDelimiter("\n");// Spaces as partitioners
				boolean flag = true; // As a circular marker
				while (flag) { // Equivalent to a constant cycle
					if (sc.hasNext()) {
						String str = sc.next().trim();// Prevent excess spaces from appearing
						if ("byebye".equalsIgnoreCase(str)) { // End of operation
							out.println("BYEBYE!!!" + str); // Respond to
							flag = false; // Represents the end of the loop
							break; // Exit loop
						}
						out.println("ECHO:" + str); // Respond to
					}
				}
				out.close();
				sc.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}

Client

import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class EchoClient {
	public static void main(String[] args) throws Exception {
		Socket cliten = new Socket("localhost", 8888);
		Scanner keyScan = new Scanner(System.in); // User input
		keyScan.useDelimiter("\n");
		Scanner netScan = new Scanner(cliten.getInputStream());
		netScan.useDelimiter("\n");
		PrintStream netOut = new PrintStream(cliten.getOutputStream());
		boolean flag = true;
		String str=null;
		while (flag) {
			System.out.print("Please enter the message to be sent:");
			if (keyScan.hasNext()) { 	 
				 str = keyScan.next().trim();
				netOut.println(str);  //Send to server
				if(netScan.hasNext()){	//The server responded
					System.out.println(netScan.next());
				}
				
				}if ("byebye".equals(str)) {
					flag = false;
					break;
				
			}
		}
		cliten.close();
		keyScan.close(); 
		netScan.close();
	}
}

 

Posted by t2birkey on Mon, 07 Oct 2019 17:57:51 -0700