java network programming connection client and server small demo

Posted by daveoliveruk on Wed, 08 Sep 2021 20:10:23 +0200

(using IDEA)
When connecting client and server according to the novice bird tutorial Newbie tutorial, simple client-to-server connection demo (https://www.runoob.com/java/java-networking.html) Some problems have been encountered:
1. Start by creating two java files, Client and Server, in the newly created java project.
(Files with two class suffixes appear after compilation)

2. Write code
Client.java

import java.net.*;
import java.io.*;

public class Client
{
    public static void main(String [] args)
    {
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);
        try
        {
            System.out.println("Connect to Host:" + serverName + ",Port number:" + port);
            Socket client = new Socket(serverName, port);
            System.out.println("Remote Host Address:" + client.getRemoteSocketAddress());
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);

            out.writeUTF("Hello from " + client.getLocalSocketAddress());
            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("Server response: " + in.readUTF());
            client.close();
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

Server.java

import java.net.*;
import java.io.*;

public class Server extends Thread
{
    private ServerSocket serverSocket;

    public Server(int port) throws IOException
    {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(10000);
    }

    public void run()
    {
        while(true)
        {
            try
            {
                System.out.println("Waiting for remote connection with port number:" + serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();
                System.out.println("Remote Host Address:" + server.getRemoteSocketAddress());
                DataInputStream in = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("Thank you for linking me:" + server.getLocalSocketAddress() + "\nGoodbye!");
                server.close();
            }catch(SocketTimeoutException s)
            {
                System.out.println("Socket timed out!");
                break;
            }catch(IOException e)
            {
                e.printStackTrace();
                break;
            }
        }
    }
    public static void main(String [] args)
    {
        int port = Integer.parseInt(args[0]);
        try
        {
            Thread t = new Server(port);
            t.run();
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

3. Compile with cmd (shortcut win+R)
(1) Server.java executes the following two commands to start the service

javac Server.java
java Server 6066

Supplementary basics: javac and java

The javac command programms the source code to a class byte code file because our JVM virtual machine executes the class byte code file, not the source code, and the JVM virtual machine does not know the source code.

Use java commands to execute class bytecode files

Note where your Server.java file exists. I have a D disk, so first enter d: open the D disk directory, then cd opens the folder.

An error was encountered running javac Server.java at this time:
1) Resolve java "Error: Unmappable characters encoding GBK"

Solution here: Encode in UTF-8, that is, change the command to javac-encoding UTF-8 Server.java

Reference Blog: Resolve java "Error: Unmappable characters encoding GBK"

(2) Client.java executes the following two commands to start the service

javac Client.java
java Client localhost 6066

There's a problem here:
2) Resolve Java errors: java.net.ConnectException: Connection refused: connect

Solution here:
Reason analysis: Server.java has been waiting too long, Socket timed out!Yes.
So, a little faster, the second command of the two files runs Client and hurries to the front foot of Server, which easily breaks the connection. (Below is the picture of Server client waiting too long resulting in Socket timed out!)

Write this part:

4. The end result is as follows:
Server.java interface

Waiting for remote connection, port number: 6066...


Client.java interface

Connect to host: localhost, port number: 6066
Remote host address: localhost/127.0.0.1:6066
Server response: Thank you for connecting me: /127.0.0.1:6066
Goodbye!

Topics: Java socket udp