Saturday, March 26, 2011

Java - Sum and Average using RMI

ServerIntf.java

import java.rmi.*;
import java.rmi.server.*;

public interface ServerIntf extends Remote {
    public double sum(double... numbers) throws RemoteException;
    public double average(double... numbers) throws RemoteException;
}



ServerImpl.java

import java.rmi.*;
import java.rmi.server.*;

public class ServerImpl extends UnicastRemoteObject implements ServerIntf {

    public ServerImpl() throws RemoteException {
    }

    public double sum(double... numbers) throws RemoteException {
        double result = 0;

        for(double num : numbers) {
            result += num;
        }

        return result;
    }

    public double average(double... numbers) throws RemoteException {
        double result = 0;
        int n = numbers.length;

        for(double num : numbers) {
            result += num;
        }

        return result/n;
    }
}



Server.java


import java.rmi.*;
import java.rmi.server.*;

public class Server {

    public static void main(String[] args) {
        try {
            ServerImpl serverImpl = new ServerImpl();
            Naming.rebind("Server", serverImpl);
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }
}





Client.java


import java.rmi.*;
import java.rmi.server.*;
import java.io.*;

public class Client {

    public static void main(String[] args) {
        try {
            String serverURL = "rmi://" + args[0] + "/Server";
            ServerIntf serverIntf = (ServerIntf)Naming.lookup(serverURL);
            BufferedReader buffRdr = new BufferedReader(new InputStreamReader(System.in));

            System.out.println("Enter the limit...");
            int n = Integer.parseInt(buffRdr.readLine());

            System.out.println("Enter the numbers...");
            double[] numbers = new double[n];
            for(int i = 0 ; i < n ; i++) {
                numbers[i] = Double.parseDouble(buffRdr.readLine());
            }

            System.out.println("Sum..." + serverIntf.sum(numbers));
            System.out.println("Average..." + serverIntf.average(numbers));
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }
}


c:\rmi\server> java Server

c:\rmi\client> java Client 127.0.0.1




NB: Refer the previous RMI programs to get an idea about how to run the program.

Tuesday, March 22, 2011

Java - System time using RMI

DateServerIntf.java


import java.rmi.*;
import java.rmi.server.*;


public interface DateServerIntf extends Remote {
    public String getSystemDate() throws RemoteException;
}





DateServerImpl.java




import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import java.text.*;

public class DateServerImpl extends UnicastRemoteObject implements DateServerIntf {

    public DateServerImpl() throws RemoteException {
    }

    public String getSystemDate() throws RemoteException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }
}




DateServer.java


import java.rmi.*;
import java.rmi.server.*;

public class DateServer {

    public static void main(String[] args) {
        try {
            DateServerImpl dateServerImpl = new DateServerImpl();
            Naming.rebind("DateServer", dateServerImpl);
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }
}





DateClient.java




import java.rmi.*;
import java.rmi.server.*;

public class DateClient {

    public static void main(String[] args) {
        try {
            String dateServerURL = "rmi://" + args[0] + "/DateServer";
            DateServerIntf dateServerIntf = (DateServerIntf)Naming.lookup(dateServerURL);
            System.out.println(dateServerIntf.getSystemDate());
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }
}



c:\rmi\server>java DateServer

c:\rmi\client> java DateClient 127.0.0.1
 
NB: Refer the previous post for directions to run a RMI program.

Java - Mathematical Operations using RMI

MathServerIntf.java

import java.rmi.*;
import java.rmi.server.*;

public interface MathServerIntf extends Remote {   

    public int add(int a, int b) throws RemoteException;

    public int subtract(int a, int b) throws RemoteException;

    public int multiply(int a, int b) throws RemoteException;

    public int divide(int a, int b) throws RemoteException;
}



MathServerImpl.java

import java.rmi.*;
import java.rmi.server.*;

public class MathServerImpl extends UnicastRemoteObject implements MathServerIntf {

    public MathServerImpl() throws RemoteException {
    }

    public int add(int a, int b) throws RemoteException {
        return a+b;
    }

    public int subtract(int a, int b) throws RemoteException {
        return a-b;
    }

    public int multiply(int a, int b) throws RemoteException {
        return a*b;
    }

    public int divide(int a, int b) throws RemoteException {
        if(b==0) {
            return -1;
        } else {
            return a/b;
        }
    }
}



MathServer.java

import java.rmi.*;
import java.rmi.server.*;

public class MathServer {

    public static void main(String[] args) {
        try {
            MathServerImpl mathServerImpl = new MathServerImpl();
            Naming.rebind("MathServer", mathServerImpl);
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }
}



MathClient.java

import java.rmi.*;
import java.rmi.server.*;
import java.io.*;

public class MathClient {

    public static void main(String[] args) {
        try {
            String mathServerURL = "rmi://" + args[0] + "/MathServer";
            MathServerIntf mathServerIntf = (MathServerIntf)
                Naming.lookup(mathServerURL);
            BufferedReader bufferedReader = new BufferedReader(
                                new InputStreamReader(System.in));

            while(true) {
           
            System.out.println("\n\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Exit\n");
            System.out.println("Enter your option...");
            int option = Integer.parseInt(bufferedReader.readLine());
           
            int number1 = 0, number2 = 0;

            if(option>=1 && option <=4) {
                System.out.println("Enter the first number...");
                number1 = Integer.parseInt(bufferedReader.readLine());

                System.out.println("Enter the second number...");
                number2 = Integer.parseInt(bufferedReader.readLine());
            }

            switch(option) {
                case 1: System.out.println("Sum...");
                    System.out.println(
                        mathServerIntf.add(number1, number2));
                    break;

                case 2: System.out.println("Difference...");
                    System.out.println(
                        mathServerIntf.subtract(number1, number2));
                    break;
       
                case 3: System.out.println("Product...");
                    System.out.println(
                        mathServerIntf.multiply(number1, number2));
                    break;
       
                case 4: System.out.println("Quotient...");
                    System.out.println(
                        mathServerIntf.divide(number1, number2));
                    break;

                case 5: System.exit(0);

                default: System.out.println("Enter a valid option...");               
            }

            }
           
                                   
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }
}



Compile the source code
> javac *.java

Create the stub class using RMI compiler
> rmic MathServerImpl

The server part consists of:
MathServerIntf.class
MathServerImpl.class
MathServer.class
MathServerImpl_Stub.class

The client part consists of:
MathClient.class
MathServerImpl_Stub.class
MathServerIntf.class


Start the RMI registry
> start rmiregistry

Run the server
> java MathServer


Run the client
> java MathClient 127.0.0.1
 



Java - TCP an example - MD, manager and employees

Question:

-> Unidirectional data transfer from the Managing Director to the Manager
-> Broadcast from the Manager to the Employees
-> Public Chat between Employees


ManagingDirector.java

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

public class ManagingDirector {
    ServerSocket serverSocket = null;
    Socket socketToManager = null;
    PrintWriter toManager = null;
    BufferedReader fromKeyboard = null;

    public ManagingDirector() {
        try {
            serverSocket = new ServerSocket(9999);
            System.out.println("Waiting for a connection...");
            socketToManager = serverSocket.accept();
            System.out.println("Connection accepted...");

            fromKeyboard = new BufferedReader(new InputStreamReader(System.in));
            toManager = new PrintWriter(socketToManager.getOutputStream());

            while(true) {
                String message = fromKeyboard.readLine();
                toManager.println(message);
                toManager.flush();
            }

        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }   

    public static void main(String[] args) {
        new ManagingDirector();
    }
}



Manager.java

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

public class Manager implements Runnable {
    ArrayList clientHandlerList = new ArrayList();
    ServerSocket serverSocket = null;
    Socket socketToMD = null;
    BufferedReader readFromMD = null;

    public Manager() {
        try {
            socketToMD = new Socket("127.0.0.1", 9999);
            readFromMD = new BufferedReader(
                new InputStreamReader(
                socketToMD.getInputStream()));

            serverSocket = new ServerSocket(9998);       
           
            new Thread(this).start();
            new Thread(new BroadCastServer(this)).start();

            while(true) {
                Socket socket = serverSocket.accept();
                ClientHandler clientHandler = new ClientHandler(socket, this);
                clientHandlerList.add(clientHandler);

                new Thread(clientHandler).start();               
            }
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }   

    public void run() {
        System.out.println("Thread started");
        try {
            while(true) {
                String message = readFromMD.readLine();
                System.out.println(message);
            }
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }

    public ArrayList getClientHandlers() {
        return clientHandlerList;
    }

    public void broadcast(String message, ClientHandler sourceHandler) {
        try {

            for(int i = 0 ; i < clientHandlerList.size() ; i++) {
                ClientHandler handler = (ClientHandler) clientHandlerList.get(i);
                if(handler != sourceHandler) {
                    handler.writeToClient.println(message);
                    handler.writeToClient.flush();
                }
            }
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Manager();
    }
}


ClientHandler.java

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

public class  ClientHandler implements Runnable {
    Manager manager = null;
    Socket socketToClient = null;
    private BufferedReader readFromClient = null;
    private BufferedReader readFromKeyboard = null;
    public PrintWriter writeToClient = null;

    public ClientHandler (Socket socketToClient, Manager manager) {
        try {
            this.socketToClient = socketToClient;
            this.manager = manager;
            readFromKeyboard = new BufferedReader(new InputStreamReader(System.in));
            readFromClient = new BufferedReader(
                new InputStreamReader(
                socketToClient.getInputStream()));
            writeToClient = new PrintWriter(socketToClient.getOutputStream());

            new Thread(this).start();
           
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }

    public void run() {
        try {
            while(true) {
                String message = readFromClient.readLine();
                manager.broadcast(message, this);
            }
        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }
}


BroadCastServer.java

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

public class BroadCastServer implements Runnable {
    private BufferedReader readFromKeyboard = null;
    Manager manager = null;

    public BroadCastServer (Manager manager) {
        this.manager = manager;
        readFromKeyboard = new BufferedReader(new InputStreamReader(System.in));
    }

    public void run() {
        try {
            while(true) {
                String message = readFromKeyboard.readLine();
                ArrayList clientHandlerList = manager.getClientHandlers();

                for(int i = 0 ; i < clientHandlerList.size() ; i++) {
                    ClientHandler handler = (ClientHandler) clientHandlerList.get(i);
                    handler.writeToClient.println(message);
                    handler.writeToClient.flush();
                }
            }

        } catch(Exception exp) {
            exp.printStackTrace();
        }
    }
}


Employee.java

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

public class Employee implements Runnable {
    Socket socket = null;
    BufferedReader readFromClient = null;
    BufferedReader readFromServer = null;
    PrintWriter writeToServer = null;

    public Employee() {
        try {
            socket = new Socket("localhost", 9998);

            readFromServer = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
            writeToServer = new PrintWriter(socket.getOutputStream());
            readFromClient = new BufferedReader(
                new InputStreamReader(System.in));

            new Thread(this).start();

            while(true) {
                String message = readFromClient.readLine();
                writeToServer.println(message);
                writeToServer.flush();
            }
        } catch(UnknownHostException exp) {
            exp.printStackTrace();
        } catch(IOException exp) {
            exp.printStackTrace();
        }
    }

    public void run() {
        try {
            while(true) {
                String message = readFromServer.readLine();
                System.out.println(message);
            }
        } catch(IOException ioExp) {
            ioExp.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Employee();
    }   
}


Friday, March 18, 2011

Java Notes for download

Saturday, March 5, 2011

Java - Bidirectional data transfer using UDP

UDPServer.java


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

public class UDPServer implements Runnable {
DatagramSocket socket = null;
DatagramPacket packetOut = null;
DatagramPacket packetIn = null;
BufferedReader readFromKeyBoard = null;
byte[] dataIn;
byte[] dataOut;

public UDPServer() {
try {
readFromKeyBoard = new BufferedReader(
new InputStreamReader(System.in));
dataIn = new byte[1024];
dataOut = new byte[1024];
socket = new DatagramSocket(997);

new Thread(this).start();

InetAddress inetAddress = InetAddress.getLocalHost();
while(true) {
String message = readFromKeyBoard.readLine();
dataIn = message.getBytes();
packetOut = new DatagramPacket(dataIn, message.length(), inetAddress, 999);
socket.send(packetOut);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
packetIn = new DatagramPacket(dataOut, dataOut.length);
socket.receive(packetIn);
String message = new String(packetIn.getData(), 0, packetIn.getLength());
System.out.println(message);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public static void main(String[] args) {
new UDPServer();
}
}



UDPClient.java

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

public class UDPClient implements Runnable {
DatagramSocket socket = null;
DatagramPacket packetOut = null;
DatagramPacket packetIn = null;
BufferedReader readFromKeyBoard = null;
byte[] dataIn;
byte[] dataOut;

public UDPClient() {
try {
readFromKeyBoard = new BufferedReader(
new InputStreamReader(System.in));
dataIn = new byte[1024];
dataOut = new byte[1024];
socket = new DatagramSocket(999);

new Thread(this).start();

InetAddress inetAddress = InetAddress.getLocalHost();
while(true) {
String message = readFromKeyBoard.readLine();
dataIn = message.getBytes();
packetOut = new DatagramPacket(dataIn, message.length(), inetAddress, 997);
socket.send(packetOut);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
packetIn = new DatagramPacket(dataOut, dataOut.length);
socket.receive(packetIn);
String message = new String(packetIn.getData(), 0, packetIn.getLength());
System.out.println(message);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public static void main(String[] args) {
new UDPClient();
}
}

Java - Public chat using GUI

Server.java

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

public class Server implements Runnable {
ServerSocket serverSocket = null;
Socket socket = null;
ArrayList clientHandlerList = new ArrayList();
ClientHandler clientHandler = null;

public Server() {
try {
serverSocket = new ServerSocket(4444);
new Thread(this).start();
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
socket = serverSocket.accept();
clientHandler = new ClientHandler(socket, this);
clientHandlerList.add(clientHandler);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void broadcast(String message, ClientHandler sourceClient) {
ClientHandler client;
for(int i = 0; i < clientHandlerList.size() ; i++ ) {
client = (ClientHandler) clientHandlerList.get(i);
if (client != sourceClient) {
client.sendMessage(message);
}
}

}

public static void main(String[] args) {
new Server();
}
}


ClientHandler.java


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

public class ClientHandler implements Runnable {
Socket socket = null;
Server server = null;
BufferedReader readFromClient = null;
PrintWriter writeToClient = null;

public ClientHandler(Socket socket, Server server) {
try {
this.socket = socket;
this.server = server;
readFromClient = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
writeToClient = new PrintWriter(socket.getOutputStream());

new Thread(this).start();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
String message = readFromClient.readLine();
server.broadcast(message, this);
}
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void sendMessage(String message) {
writeToClient.println(message);
writeToClient.flush();
}
}


Client.java


import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Client extends JFrame implements Runnable, ActionListener {
Socket socket = null;
BufferedReader readFromClient = null;
BufferedReader readFromServer = null;
PrintWriter writeToServer = null;
JTextField chatField = null;
JTextArea chatArea = null;
JButton sendButton = null;

public Client() {
try {
initComponents();
socket = new Socket("localhost", 4444);

readFromServer = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
writeToServer = new PrintWriter(socket.getOutputStream());
readFromClient = new BufferedReader(
new InputStreamReader(System.in));

new Thread(this).start();


} catch(UnknownHostException exp) {
exp.printStackTrace();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void initComponents() {
setSize(270,507);
setResizable(false);
setLayout(null);
chatArea = new JTextArea();
chatField = new JTextField(20);
chatArea.setForeground(Color.BLACK);
sendButton = new JButton("SEND");
chatArea.setEditable(false);
chatArea.setBounds(5,5,250,400);
chatField.setBounds(5,410,250,30);
sendButton.setBounds(175,450,80,20);
sendButton.addActionListener(this);

chatField.addKeyListener( new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
sendButtonAction();
}
}
});

add(chatArea);
add(chatField);
add(sendButton);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(this);
}

public void actionPerformed(ActionEvent evt) {
if(evt.getSource() == sendButton) {
sendButtonAction();
}
}

public void sendButtonAction() {
String message = chatField.getText();
chatField.setText("");
chatArea.append(message + "\n");
writeToServer.println(message);
writeToServer.flush();
}

public void run() {
try {
while(true) {
String message = readFromServer.readLine();
chatArea.append(message + "\n");
}
} catch(IOException ioExp) {
ioExp.printStackTrace();
}
}

public static void main(String[] args) {
new Client().setVisible(true);
}
}









Java - Data broadcasting using GUI

Server.java

import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Server extends JFrame implements Runnable, ActionListener {
ServerSocket serverSocket = null;
Socket socket = null;
ArrayList clientHandlerList = new ArrayList();
ClientHandler clientHandler = null;
JTextField chatField = null;
JTextArea chatArea = null;
JButton sendButton = null;

public Server() {
try {
initComponents();
serverSocket = new ServerSocket(4444);
new Thread(this).start();
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void initComponents() {
setSize(270,507);
setResizable(false);
setLayout(null);
chatArea = new JTextArea();
chatField = new JTextField(20);
chatArea.setForeground(Color.BLACK);
sendButton = new JButton("SEND");
chatArea.setEditable(false);
chatArea.setBounds(5,5,250,400);
chatField.setBounds(5,410,250,30);
sendButton.setBounds(175,450,80,20);
sendButton.addActionListener(this);

chatField.addKeyListener( new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
sendButtonAction();
}
}
});

add(chatArea);
add(chatField);
add(sendButton);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(this);
}

public void actionPerformed(ActionEvent evt) {
if(evt.getSource() == sendButton) {
sendButtonAction();
}
}

public void sendButtonAction() {
String message = chatField.getText();
chatField.setText("");
chatArea.append(message + "\n");
broadcast(message);
}

public void run() {
try {
while(true) {
socket = serverSocket.accept();
clientHandler = new ClientHandler(socket, this);
clientHandlerList.add(clientHandler);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void broadcast(String message) {
ClientHandler client;
for(int i = 0; i < clientHandlerList.size() ; i++ ) {
client = (ClientHandler) clientHandlerList.get(i);
client.sendMessage(message);
}

}

public static void main(String[] args) {
new Server().setVisible(true);
}
}


ClientHandler.java


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

public class ClientHandler {
Socket socket = null;
Server server = null;
PrintWriter writeToClient = null;

public ClientHandler(Socket socket, Server server) {
try {
this.socket = socket;
this.server = server;
writeToClient = new PrintWriter(socket.getOutputStream());
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void sendMessage(String message) {
writeToClient.println(message);
writeToClient.flush();
}
}

Client.java

import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Client extends JFrame implements Runnable {
Socket socket = null;
BufferedReader readFromServer = null;
JTextArea chatArea = null;

public Client() {
try {
initComponents();
socket = new Socket("localhost", 4444);

readFromServer = new BufferedReader(
new InputStreamReader(socket.getInputStream()));

new Thread(this).start();

} catch(UnknownHostException exp) {
exp.printStackTrace();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void initComponents() {
setSize(270,480);
setResizable(false);
setLayout(null);
chatArea = new JTextArea();
chatArea.setForeground(Color.BLACK);
chatArea.setEditable(false);
chatArea.setBounds(5,5,250,400);

add(chatArea);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(this);
}

public void run() {
try {
while(true) {
String message = readFromServer.readLine();
chatArea.append(message + "\n");
}
} catch(IOException ioExp) {
ioExp.printStackTrace();
}
}

public static void main(String[] args) {
new Client().setVisible(true);
}
}

Java - Public chat

Server.java

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

public class Server implements Runnable {
ServerSocket serverSocket = null;
Socket socket = null;
ArrayList clientHandlerList = new ArrayList();
ClientHandler clientHandler = null;

public Server() {
try {
serverSocket = new ServerSocket(4444);
new Thread(this).start();
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
socket = serverSocket.accept();
clientHandler = new ClientHandler(socket, this);
clientHandlerList.add(clientHandler);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void broadcast(String message, ClientHandler sourceClient) {
ClientHandler client;
for(int i = 0; i < clientHandlerList.size() ; i++ ) {
client = (ClientHandler) clientHandlerList.get(i);
if (client != sourceClient) {
client.sendMessage(message);
}
}

}

public static void main(String[] args) {
new Server();
}
}


ClientHandler.java


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

public class ClientHandler implements Runnable {
Socket socket = null;
Server server = null;
BufferedReader readFromClient = null;
PrintWriter writeToClient = null;

public ClientHandler(Socket socket, Server server) {
try {
this.socket = socket;
this.server = server;
readFromClient = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
writeToClient = new PrintWriter(socket.getOutputStream());

new Thread(this).start();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
String message = readFromClient.readLine();
server.broadcast(message, this);
}
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void sendMessage(String message) {
writeToClient.println(message);
writeToClient.flush();
}
}


Client.java

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

public class Client implements Runnable {
Socket socket = null;
BufferedReader readFromClient = null;
BufferedReader readFromServer = null;
PrintWriter writeToServer = null;

public Client() {
try {
socket = new Socket("localhost", 4444);

readFromServer = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
writeToServer = new PrintWriter(socket.getOutputStream());
readFromClient = new BufferedReader(
new InputStreamReader(System.in));

new Thread(this).start();

while(true) {
String message = readFromClient.readLine();
writeToServer.println(message);
writeToServer.flush();
}
} catch(UnknownHostException exp) {
exp.printStackTrace();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
String message = readFromServer.readLine();
System.out.println(message);
}
} catch(IOException ioExp) {
ioExp.printStackTrace();
}
}

public static void main(String[] args) {
new Client();
}
}

Java - Data broadcasting

Server.java

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

public class Server implements Runnable {
ServerSocket serverSocket = null;
Socket socket = null;
ArrayList clientHandlerList = new ArrayList();
ClientHandler clientHandler = null;
BufferedReader readFromKeyboard = null;

public Server() {
try {
serverSocket = new ServerSocket(4444);
readFromKeyboard = new BufferedReader(
new InputStreamReader(System.in));
new Thread(this).start();

while(true) {
String message = readFromKeyboard.readLine();
broadcast(message);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
socket = serverSocket.accept();
clientHandler = new ClientHandler(socket, this);
clientHandlerList.add(clientHandler);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void broadcast(String message) {
ClientHandler client;
for(int i = 0; i < clientHandlerList.size() ; i++ ) {
client = (ClientHandler) clientHandlerList.get(i);
client.sendMessage(message);
}

}

public static void main(String[] args) {
new Server();
}
}


ClientHandler.java

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

public class ClientHandler {
Socket socket = null;
Server server = null;
PrintWriter writeToClient = null;

public ClientHandler(Socket socket, Server server) {
try {
this.socket = socket;
this.server = server;
writeToClient = new PrintWriter(socket.getOutputStream());
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void sendMessage(String message) {
writeToClient.println(message);
writeToClient.flush();
}
}


Client.java

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

public class Client implements Runnable {
Socket socket = null;
BufferedReader readFromServer = null;

public Client() {
try {
socket = new Socket("localhost", 4444);

readFromServer = new BufferedReader(
new InputStreamReader(socket.getInputStream()));

new Thread(this).start();

} catch(UnknownHostException exp) {
exp.printStackTrace();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
String message = readFromServer.readLine();
System.out.println(message);
}
} catch(IOException ioExp) {
ioExp.printStackTrace();
}
}

public static void main(String[] args) {
new Client();
}
}

Java - Bidirectional Data transfer using TCP



ServerThread.java


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

public class ServerThread implements Runnable {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader readFromClient = null;
BufferedReader readFromServer = null;
PrintWriter writeToClient = null;
String message = null;

public ServerThread() {
try {
serverSocket = new ServerSocket(4444);
System.out.println("Waiting for connection...");
socket = serverSocket.accept();
System.out.println("Connection accepted...");

readFromClient = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
writeToClient = new PrintWriter(
socket.getOutputStream(), true);
readFromServer = new BufferedReader(
new InputStreamReader(
System.in));

new Thread(this).start();

while(true) {
message = readFromServer.readLine();
writeToClient.println(message);
writeToClient.flush();
if(message.equalsIgnoreCase("exit")) {
System.exit(0);
}
}

} catch(IOException exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
String msg = readFromClient.readLine();
if(!msg.equalsIgnoreCase("exit")) {
System.out.println(msg);
} else {
System.exit(0);
}
}
} catch(Exception exp) {
exp.printStackTrace();
}
}
}

Server.java


public class Server {
public static void main(String[] args) {
new ServerThread();
}
}

ClientThread.java

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

public class ClientThread implements Runnable {
Socket socket = null;
BufferedReader readFromClient = null;
BufferedReader readFromServer = null;
PrintWriter writeToServer = null;
String message = null;

public ClientThread(Socket socket) {
try {
this.socket = socket;
readFromServer = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
writeToServer = new PrintWriter(
socket.getOutputStream(), true);
readFromClient = new BufferedReader(
new InputStreamReader(System.in));

new Thread(this).start();

while(true) {
message = readFromClient.readLine();
writeToServer.println(message);
writeToServer.flush();
if(message.equalsIgnoreCase("exit")) {
System.exit(0);
}
}
} catch(IOException exp) {
exp.printStackTrace();
}
}


public void run() {
try {
while(true) {
String msg = readFromServer.readLine();
if(!msg.equalsIgnoreCase("exit")) {
System.out.println(msg);
} else {
System.exit(0);
}
}
} catch(Exception exp) {
exp.printStackTrace();
}
}
}


Client.java

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

public class Client {
Socket socket = null;


public Client() {
try {
socket = new Socket("localhost",4444);
new ClientThread(socket);
} catch(UnknownHostException exp) {
exp.printStackTrace();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public static void main(String[] args) {
new Client();
}
}


Java - Select Statament - My SQL



String[] names = new String[100];
Connection con = getConnection();
String query = "SELECT name FROM student";
PreparedStatement preparedStatement = con.prepareStatement(query);

ResultSet resultSet = preparedStatement.executeQuery();

int i=0;
while(resultSet.next()) {
       names[i] = resultSet.getString("name"); // name is the field name
       i++;
}

Java - Insert Statement - My SQL




String rollno = "1";
String name = "ABC";
Connection con = getConnection();

String query = "insert into student (rollno, name) values (?,?)";
/*student is the table name, rollno and name are the field names*/

PreparedStatement preparedStatement = con.prepareStatement(query);

preparedStatement.setString(1,rollno);
preparedStatement.setString(2,name);

/*
*  String query = "insert into student (rollno, name) values ('1','ABC')";
*  PreparedStatement preparedStatement = con.prepareStatement(query);
*
*  NB: This is also correct. First format is used if the inputs are from user through JTextField.
*/

int noOfRowsUpdated = preparedStatement.executeUpdate();

Java - Getting current time and date

private String getDateTime()  {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
}

Date currentDateAndTime = getDateTime();

Java - Giving background picture to a JFrame

Image bgImage = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/src/ui/images/abc.jpg"));

public void paintComponent(Graphics g) {
        g.drawImage(bgImage,0,0,this);
}
 

Java - Database connectivity My SQL

public Connection getConnection() {
       Connection con=null;
       try {
              Class.forName("com.mysql.jdbc.Driver");
              con = DriverManager.getConnection(
              "jdbc:mysql://127.0.0.1/databaseName","userName","password");
       } catch(Exception e) {
              System.out.println(e);
       }
       return con;
}

Java - Getting Computer Name


public class GetComputerName {

    public static void main(String args[]) {
        try {
            String computerName = InetAddress.getLocalHost().getHostName();
            System.out.println(computerName);
        } catch (Exception e) {
            System.out.println("Exception caught =" + e.getMessage());
        }
    }
}

Contact Form

Name

Email *

Message *

The Insane Techie - Android App

Launched an android app for the blog on 07th June 2016. Get it from google play store... Tips for using the app Use in landscape mo...