Netbeans Multi Client Server (NMCS)


NMCS:   SOLD       




We present a material that is the result of completing Assignment 2 Multi Client Server in the Network Programming course, guided by Mr. Untung Subagyo, S.Kom. This program was created using Netbeans IDE version 8.2.


Figure 1 - Java Multi Client Server Programming

Case study:

Create a server-client program using TCP Socket. First activate the server. For example, on the client type "salam" then this string will be sent to the server, on the server the string will be reversed so that it becomes "malas". The reversed string is then sent back to the client.

Meanwhile, the server displays the message:

Message received <no pesan> : <pesan yang dikirim>

The client will display the message:

SERVER Message <no pesan> : <pesan dari server yang sudah di balik>

Solution:

Step 1 -- Preparing the Project

  1. Open NetBeans IDE Application
  2. Create a Java application project with the name "MultiEchoServer"
  3. Create a Java application project with the name "MultiEchoClient"

Step 2 -- Download the Source Code HERE

Step 3 -- Adopt the Downloaded Source Code

  1. Adopt MultiEchoServer.java source code for "MultiEchoServer" project
  2. Adopt MultiEchoClient.java source code for "MultiEchoClient" project

Step 4 -- Modify MultiEchoServer Code

Modify the run() method section so that it looks like this:


Figure 2 - Modifying the run() Method

Information:

  • Declare variable no=0; //this variable is used to identify incoming messages from the client.
  • no++; //increment operator, to add the value of no. by 1, as the loop progresses.
  • Int length //variable that adopts the length of the string, which is used for loop parameters.

Adjust the displayed messages as specified in the case study, namely:

  • System.out.println("Message received #no:" + no +" "+ received); //displays the client message and its number.
  • out.println("SERVER Message #no:" + no +" "+ balik); //displays the returned server response and its message number.

Capture


Figure 3. Client A Message and Feedback from Server


Figure 4. Client B Message and Feedback from Server


Figure 5. Server Response to Client A and Client B

Source Code More

Maybe someone wants to adopt the source code only.

MultiEchoServer.java

package multiechoserver;
import java.io.*;
import java.net.*;
public class MultiEchoServer {
    private static ServerSocket servSock;
    private static final int PORT = 12345;

    public static void main(String[] args) throws IOException{
        System.out.println("Opening Port....\n");
        try {
            servSock = new ServerSocket(PORT);

        } catch (Exception e) {
            System.out.println("Unable to attach to port");
            System.exit(1);
        }
        do {
            Socket client = servSock.accept();
            ClientHander handler = new ClientHander(client);
            handler.start();
        } while (true);
    }

}

class ClientHander extends Thread{
    private Socket client;
    private BufferedReader in;
    private PrintWriter out;

    public ClientHander(Socket socket){
        client = socket;

        try {
            in = new BufferedReader (
            new InputStreamReader(client.getInputStream())
            );
            out = new PrintWriter(client.getOutputStream(),true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
/* Wawan Chahyo Nugroho NIM:12131294 */
        public void run(){
            try{
                String received, balik=""; //tambahkan variabel balik untuk manampung pembalikan
                Integer no=0; //variabel no. untuk identifikasi pesan dari client
                do{
                    received = in.readLine();
                    no++; //penambahan nilai no. seiring berjalannya looping

                    /*Perulangan yang digunakan untuk membalik pesan client
                    dengan memanfaatkan length string untuk mengambil ekor stringnya*/
                    int panjang = received.length();
                    for (int i= panjang-1; i >= 0; i--){
                        balik = balik+received.charAt(i);
                    }
                    System.out.println("Message received #no:" + no +" "+ received); //menampilkan pesan client beserta no.nya
                    out.println("SERVER Message #no:" + no +" "+ balik); //menampilkan respon server yang sudah dibalik dan beserta no.pesannya.
                    balik=""; //untuk mereset variabel balik.
                }while(!received.equals("QUIT"));
            }catch(IOException e){
                e.printStackTrace();
            }
            finally{
                try{
                    if (client != null){
                        System.out.println("Closing down connection");
                        client.close();
                    }
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
}

MultiEchoClient.java

package multiechoclient;
import java.io.*;
import java.net.*;

public class MultiEchoClient {
    private static InetAddress host;
    private static final int PORT = 12345;
    private static Socket link;
    private static BufferedReader in;
    private static PrintWriter out;
      private static BufferedReader keyboard;
    public static void main(String[] args) {
        try {
            host = InetAddress.getLocalHost();
            link = new Socket(host,PORT);
            in = new BufferedReader(new InputStreamReader(link.getInputStream()));
            out = new PrintWriter(link.getOutputStream(),true);
            keyboard = new BufferedReader(new InputStreamReader(System.in));
            String message, response;
            do {
                System.out.println("Enter message (QUIT to exit)");
                message = keyboard.readLine();
                out.println(message);
                response = in.readLine();
                System.out.println(response);

            } while (!message.equals("QUIT"));
        } catch (UnknownHostException e) {
            System.out.println("Host ID not found!");
        }
        catch(IOException e){ e.printStackTrace();
        }
        finally{
            try {
                if (link != null){
                    System.out.println("Closing down connection");
                    link.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Mission Completed!

Client-Server Send Messages Using Sockets

What needs to be done with this java program?

  1. Leveraging java socket programming
  2. Starting with a running server listening on port 25000 (Server.java)
  3. Client (Client.java) sends number(message) to server
  4. The server receives the number and multiplies it by 2.
  5. The server (Server.java) sends back the result (message) to the client (Client.java)
  6. In case of an error in the number sent by the client, the server responds with the message "Please send the correct number!" to the client.

Note: Run Server.java for the first time, because the server must be ready before the client sends messages.

Server.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{

    private static Socket socket;

    public static void main(String[] args)
    {
        try
        {

            int port = 25000;
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Server Started and listening to the port 25000");

            //Server is running always. This is done using this while(true) loop
            while(true)
            {
                //Reading the message from the client
                socket = serverSocket.accept();
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String number = br.readLine();
                System.out.println("Message received from client is "+number);

                //Multiplying the number by 2 and forming the return message
                String returnMessage;
                try
                {
                    int numberInIntFormat = Integer.parseInt(number);
                    int returnValue = numberInIntFormat*2;
                    returnMessage = String.valueOf(returnValue) + "\n";
                }
                catch(NumberFormatException e)
                {
                    //Input was not a number. Sending proper message back to client.
                    returnMessage = "Please send a proper number\n";
                }

                //Sending the response back to the client.
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                bw.write(returnMessage);
                System.out.println("Message sent to the client is "+returnMessage);
                bw.flush();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                socket.close();
            }
            catch(Exception e){}
        }
    }
}

Client.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

public class Client
{

    private static Socket socket;

    public static void main(String args[])
    {
        try
        {
            String host = "localhost";
            int port = 25000;
            InetAddress address = InetAddress.getByName(host);
            socket = new Socket(address, port);

            //Send the message to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            String number = "2";

            String sendMessage = number + "\n";
            bw.write(sendMessage);
            bw.flush();
            System.out.println("Message sent to the server : "+sendMessage);

            //Get the return message from the server
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String message = br.readLine();
            System.out.println("Message received from the server : " +message);
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
            //Closing the socket
            try
            {
                socket.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

Have a good study!


Post a Comment

Previous Next

نموذج الاتصال