Server processing with Java (Introduction part.1)

Studying server in Java

Target

  1. Review of server basics
  2. Start a server that returns a character string to the accessing client in your personal computer.
  3. Access the server as a client in your personal computer and receive the character string
  4. Added the function to display the character string sent from the client to the server.
  5. Added the ability to send strings to clients
  6. Display the input character string on the server side
  7. Display the client's IP address on the server side
  8. Display the time when the character string was sent from the client
  9. When a character string is sent from the client side, the number of the accessing client is stored in the server and displayed (the counter is set to 0 when the server starts).
  10. Make the string sent from the client to the server multiple lines
  11. Make the string sent from the server to the client multiple lines

Main story

1. Review of server basics

1. Start the server that displays the character string on the client side in your personal computer.

Create the following file Create

basic01Server.java


import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class basic01Server {
    public static void main(String[] args) {
        try{
            ServerSocket server = new ServerSocket(3838, 5);
            while(true){
                System.out.println("The server is running.");
                Socket socket = server.accept();
                PrintWriter output = new PrintWriter(socket.getOutputStream());
                output.println("Hello! This is a server!");
                output.close();     //PrintWriter is close()Basically close with
                socket.close();     //Socket is close()Basically close with
            }
        } catch (Exception e){
            System.out.println(e);
        }
    }
}

Compile and start.

2. Access the server as a client in your personal computer and receive the character string

Create the following files

basic01Client.java


import java.net.Socket;
import java.util.Scanner;
public class basic01Client {
    public static void main(String[] args) {
        try{
            Socket socket = new Socket("127.0.0.1", 3838);          //Use localhost server
            Scanner input = new Scanner(socket.getInputStream());
            System.out.println("The message from the server is "" + input.nextLine() + "」");
            input.close();          //Scanner close()Basically close with
            socket.close();         //Socket is close()Basically close with
        } catch (Exception e){
            System.out.println(e);
        }
    }
}

Let's run

3. Added the function to display the character string sent from the client to the server.

basic01Server02.java


import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;       //add to
public class basic01Server02 {
    public static void main(String[] args) {
        try{
            ServerSocket server = new ServerSocket(3838, 5);
            while(true){
                System.out.println("The server is running.");
                Socket socket = server.accept();
				Scanner input = new Scanner(socket.getInputStream());       //add to:Stores the string received from the client
				System.out.println("The message sent from the client is "" + input.nextLine() + ""is");   //add to:Output the stored character string
                PrintWriter output = new PrintWriter(socket.getOutputStream());
                output.println("Hello! This is a server!");
                output.close();
                socket.close();
            }
        } catch (Exception e){
            System.out.println(e);
        }
    }
}


I haven't done it yet

4. Added the ability to send strings to clients

basic01Client02.java


import java.net.Socket;
import java.util.Scanner;
import java.io.PrintWriter;     // add
import java.io.*;               // add
public class basic01Client02 {
    public static void main(String[] args) {
        try{
            Socket socket = new Socket("127.0.0.1", 3838);
			PrintWriter output = new PrintWriter(socket.getOutputStream());         // add
			output.println("Send string from client");                         // add
			output.flush();
            Scanner input = new Scanner(socket.getInputStream());
            System.out.println("The message from the server is "" + input.nextLine() + "」");
            input.close();
            output.close();         // add
            socket.close();
        } catch (Exception e){
            System.out.println(e);
        }
    }
}


Let's run

2. Display the input string on the server side

Rewrite the file on the client side.

basic02Client.java


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class basic02Client {
	public static void main(String args[]){
		try{
			Socket socket = new Socket("127.0.0.1", 3838);
			PrintWriter output = new PrintWriter(socket.getOutputStream());
			BufferedReader consoleIn = new BufferedReader( new InputStreamReader(System.in) );      // add
			String consoleInStr = consoleIn.readLine();         // add
			//output.println("----");       // remove
			output.println(consoleInStr);   // add
			output.flush();
			Scanner input = new Scanner(socket.getInputStream());
			System.out.println(input.nextLine());
			input.close();
			output.close();
			socket.close();
		} catch(Exception e){
			System.out.println(e);
		}
	}
}

Reference: Enter a string from the Java keyboard

3. Display the client's IP address on the server side

basic03Server.java


import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class basic03Server {
    public static void main(String[] args) {
        try{
            ServerSocket server = new ServerSocket(3838, 5);
            while(true){
                System.out.println("The server is running.");
                Socket socket = server.accept();
				Scanner input = new Scanner(socket.getInputStream());
				System.out.println("The message sent from the client is "" + input.nextLine() + ""is");
                String clientIpAddress = socket.getRemoteSocketAddress().toString();                        // add:1
                System.out.println( "The IP address and port number of the client is "" + clientIpAddress + "」");     // add
                String clientIpAddr = socket.getInetAddress().getHostAddress().toString();                  // add:2
                System.out.println( "The IP address and port number of the client is "" + clientIpAddr + "」");        // add
                PrintWriter output = new PrintWriter(socket.getOutputStream());
                output.println("Hello! This is a server!");
                output.close();
                socket.close();
            }
        } catch (Exception e){
            System.out.println(e);
        }
    }
}

Reference: How to find the IP Address of Client connected to Server? --Stack overflow

4. Display the time when the character string was sent from the client

basic04Server.java


import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Date;
public class basic04Server {
    public static void main(String[] args) {
        try{
            ServerSocket server = new ServerSocket(3838, 5);
            while(true){
                System.out.println("The server is running.");
                Socket socket = server.accept();
				Scanner input = new Scanner(socket.getInputStream());
				System.out.println("The message sent from the client is "" + input.nextLine() + ""is");
                String clientIpAddress = socket.getRemoteSocketAddress().toString();
                System.out.println( "The IP address and port number of the client is "" + clientIpAddress + "」");
                String clientIpAddr = socket.getInetAddress().getHostAddress().toString();
                System.out.println( "The IP address and port number of the client is "" + clientIpAddr + "」");
                Date time = new Date();                                     // add
                System.out.println( "Times of Day:"" + time + "」");              // add
                PrintWriter output = new PrintWriter(socket.getOutputStream());
                output.println("Hello! This is a server!");
                output.close();
                socket.close();
            }
        } catch (Exception e){
            System.out.println(e);
        }
    }
}

5. When a character string is sent from the client side, the number of the accessing client is stored in the server and displayed (the counter is set to 0 when the server starts).

basic05Server.java


import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Date;
public class basic05Server {
    public static void main(String[] args) {
        try{
            ServerSocket server = new ServerSocket(3838, 5);
            int order = 0;              // add
            while(true){
                System.out.println("The server is running.");
                Socket socket = server.accept();
                order += 1;             // add
				Scanner input = new Scanner(socket.getInputStream());
				System.out.println("The message sent from the client is "" + input.nextLine() + ""is");
                String clientIpAddress = socket.getRemoteSocketAddress().toString();
                System.out.println( "The IP address and port number of the client is "" + clientIpAddress + "」");
                String clientIpAddr = socket.getInetAddress().getHostAddress().toString();
                System.out.println( "The IP address and port number of the client is "" + clientIpAddr + "」");
                Date time = new Date();
                System.out.println( "Times of Day:"" + time + "」");
                System.out.println( "This client is "" + order + "It is the third.");
                PrintWriter output = new PrintWriter(socket.getOutputStream());
                output.println("Hello! This is a server!");
                output.close();
                socket.close();
            }
        } catch (Exception e){
            System.out.println(e);
        }
    }
}

6. Make the string sent from the client to the server multiple lines

basic06Server.java


import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Date;
public class basic06Server {
    public static void main(String[] args) {
        try{
            ServerSocket server = new ServerSocket(3838, 5);
            int order = 0;              // add
            while(true){
                System.out.println("The server is running.");
                Socket socket = server.accept();
                order += 1;             // add
				Scanner input = new Scanner(socket.getInputStream());
				System.out.println("The message sent from the client is "");   // change
                String getString = input.nextLine();
                while(!getString.equals("QUIT")){                                   // change:"QUIT"End when the character string of
                    System.out.println(getString);                                  // change
                    getString = input.nextLine();                                   // add
                }
				System.out.println(""is");                                       // change
                String clientIpAddress = socket.getRemoteSocketAddress().toString();
                System.out.println( "The IP address and port number of the client is "" + clientIpAddress + "」");
                String clientIpAddr = socket.getInetAddress().getHostAddress().toString();
                System.out.println( "The IP address and port number of the client is "" + clientIpAddr + "」");
                Date time = new Date();
                System.out.println( "Times of Day:"" + time + "」");
                System.out.println( "This client is "" + order + "It is the third.");
                PrintWriter output = new PrintWriter(socket.getOutputStream());
                output.println("Hello! This is a server!");
                output.close();
                socket.close();
            }
        } catch (Exception e){
            System.out.println(e);
        }
    }
}

basic06Client.java


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class basic06Client {
	public static void main(String args[]){
		try{
			Socket socket = new Socket("127.0.0.1", 3838);
			PrintWriter output = new PrintWriter(socket.getOutputStream());
			BufferedReader consoleIn = new BufferedReader( new InputStreamReader(System.in) );
			//String consoleInStr = consoleIn.readLine();       // remove
			String consoleInStr = "";                           // add
            while(!consoleInStr.equals("QUIT")){                // change:"QUIT"Enter to finish
			    consoleInStr = consoleIn.readLine();
                output.println(consoleInStr);
                output.flush();
            }
			Scanner input = new Scanner(socket.getInputStream());
			System.out.println(input.nextLine());
			input.close();
			output.close();
			socket.close();
		} catch(Exception e){
			System.out.println(e);
		}
	}
}

Reference: Comparison of character strings with character strings

7. Make the string sent from the server to the client multiple lines

basic07Server.java


import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Date;
public class basic07Server {
    public static void main(String[] args) {
        try{
            ServerSocket server = new ServerSocket(3838, 5);
            int order = 0;              // add
            while(true){
                System.out.println("The server is running.");
                Socket socket = server.accept();
                order += 1;             // add
				Scanner input = new Scanner(socket.getInputStream());
				System.out.println("The message sent from the client is "");
                String getString = input.nextLine();
                while(!getString.equals("QUIT")){
                    System.out.println(getString);
                    getString = input.nextLine();
                }
				System.out.println(""is");
                String clientIpAddress = socket.getRemoteSocketAddress().toString();
                System.out.println( "The IP address and port number of the client is "" + clientIpAddress + "」");
                String clientIpAddr = socket.getInetAddress().getHostAddress().toString();
                System.out.println( "The IP address and port number of the client is "" + clientIpAddr + "」");
                Date time = new Date();
                System.out.println( "Times of Day:"" + time + "」");
                System.out.println( "This client is "" + order + "It is the third.");
                PrintWriter output = new PrintWriter(socket.getOutputStream());
                //Multiple messages to return to the client
                output.println( "START SERVER MESSAGE");                // add
                output.println( "-------------------------------");     // add
                output.println( "Hello!" );                       // add
                output.println( "This is a server." );             // add
                output.println( "Sends a multi-line string.");          // add   
                output.println( "-------------------------------");     // add   
                output.println( "END SERVER MESSAGE");                  // add   
                //output.println("Hello! This is a server!");         // remove
                output.close();
                socket.close();
            }
        } catch (Exception e){
            System.out.println(e);
        }
    }
}

basic07Client.java


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class basic07Client {
	public static void main(String args[]){
		try{
			Socket socket = new Socket("127.0.0.1", 3838);
			PrintWriter output = new PrintWriter(socket.getOutputStream());
			BufferedReader consoleIn = new BufferedReader( new InputStreamReader(System.in) );
			String consoleInStr = "";
            while(!consoleInStr.equals("QUIT")){
			    consoleInStr = consoleIn.readLine();
                output.println(consoleInStr);
                output.flush();
            }
			Scanner input = new Scanner(socket.getInputStream());
            String serverMessage = "";                              // add
            while(!serverMessage.equals("END SERVER MESSAGE")){     // add
                serverMessage = input.nextLine();                   // add
                System.out.println(serverMessage);                  // add
            }                                                       // add
			input.close();
			output.close();
			socket.close();
		} catch(Exception e){
			System.out.println(e);
		}
	}
}

Recommended Posts

Server processing with Java (Introduction part.1)
Understanding Java Concurrent Processing (Introduction)
Java to learn with ramen [Part 1]
100% Pure Java BDD with JGiven (Introduction)
[Java] Introduction
I tried OCR processing a PDF file with Java part2
Introduction to Java that can be understood even with Krillin (Part 1)
Introduction to algorithms with java --Search (depth-first search)
Getting Started with Java Starting from 0 Part 1
AWS Lambda with Java starting now Part 1
Install Docker with WSL2 Memo ([Part 2] Docker introduction)
Introduction to algorithms with java --Search (breadth-first search)
Java thread processing
Java string processing
[Java] Introduction to Java
Introduction to java
[Java] Multi-thread processing
Christmas with Processing
[Java] Stream processing
java iterative processing
Introduction to algorithms with java --Search (bit full search)
Simple obstacle racing made with processing for Java
Road to Java Engineer Part1 Introduction & Environment Construction
JSON with Java and Jackson Part 2 XSS measures
Install java with Homebrew
List processing to understand with pictures --java8 stream / javaslang-
[Java] Find prime numbers with an Eratosthenes sieve (Part 2)
Introduction of Docker --Part 1--
SaveAsBinaryFile with Spark (Part 2)
Change seats with java
Install Java with Ansible
Play down with Raspberry PI4 as a server. Part 2
Comfortable download with JAVA
Quick learning Java "Introduction?" Part 2 Let's write the process
Switch java with direnv
I tried OCR processing a PDF file with Java
HTTPS connection with Java to the self-signed certificate server
Download Java with Ansible
Studying Java ~ Part 8 ~ Cast
JAVA constructor call processing
Let's scrape with Java! !!
Introduction to java command
JPS (Java Server pages)
Java random, various processing
Build Java with Wercker
Replace only part of the URL host with java
Quick learning Java "Introduction?" Part 3 Talking away from programming
Endian conversion with JAVA
Implementing a large-scale GraphQL server in Java with Netflix DGS
JSON in Java and Jackson Part 1 Return JSON from the server
List processing to understand with pictures --java8 stream / javaslang --bonus
Solving with Ruby, Perl and Java AtCoder ABC 129 C (Part 1)
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Doma-Annotation Processing
Getting Started with Java Collection
Bean mapping with MapStruct Part 1
45 Java Performance Optimization Techniques (Part 1)
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient