0

Suppose i have 3 classes. Classes are Login, HandleMultipleClients and LiveMonitoring class.In login class i am connected server to multiple clients and send the socket to Handle multiple class In this class i am making a list of clients that are connected to server and put these clients into an array.In HandleMultipleClients there is one more function which sends the message to specific clients of my choice on the base of ipaddress. Now in Live monitoring class i want to send message to a specific client i call the handlemultipleclients as new Handlemultipleclients() and make an object so this new object isn't have any list of clients like above made.i want to know that is there any method by which i dont need to make a new object of handlemultipleclients class My codes are

public class Login implements Runnable {
     @Override
     public void run() {
         try {
             serverSock = new ServerSocket(2101);
             while (true) {
                 sock = serverSock.accept();
                 LiveMOnitoring l=new LiveMOnitoring(sock);
                 System.out.println(sock);
                 //clients.put(soc.getPort(),soc);
             }
         }
     } 
}

public HandleMultipleClients(Socket sock) {
    soc=sock;
    clients.put(soc.getPort(),soc);
}

public void messagetospecificclients(String ipaddress,String choice) throws IOException, InterruptedException {
    System.out.print(ipaddress+"\n"+choice);
    for (Iterator<Integer> iter = clients.keySet().iterator(); iter.hasNext(); ) {
        System.out.print("ok1");
        int key = iter.next();
        java.net.Socket client = clients.get(key);
        InetAddress zee = client.getInetAddress();
        String s = zee.getHostAddress();
        System.out.print(s);
        if (zee.getHostAddress().equals(ipaddress)) {
            System.out.print("ok2");
            dos =new DataOutputStream(client.getOutputStream());
            dos.writeUTF(choice);
        }
    }
}


public class LiveMOnitoring extends javax.swing.JFrame {
    static Socket csocket;
    DataOutputStream dos;
    Map<Integer, java.net.Socket> clients = new HashMap<Integer, java.net.Socket> ();
    private void ApplicationsActionPerformed(java.awt.event.ActionEvent evt) {                                             
        h.messagetospecificclients();
    }
}
Tan Li Hau
  • 1,984
  • 17
  • 24
zeeshan nisar
  • 553
  • 2
  • 4
  • 18

2 Answers2

2

In Java, if you want to use a member method without instantiating a class, then you make the method static.

class A
{
   public static void methodName ()
   {

   }
}

Call it with A.methodName();

Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
0

That's what you can use static for.

read here for more: Calling method without object

Community
  • 1
  • 1
zython
  • 1,176
  • 4
  • 22
  • 50