Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.7 kB
2
Indexable
Never
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package temperatureserverimplbs;
import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import temperaturelistenerbs.TemperaturelistenerBS;
import temperatureserverbs.TemperatureServerBS;
public class TemperatureServerImplBS extends UnicastRemoteObject implements TemperatureServerBS, 
 Runnable
{
 private List<TemperaturelistenerBS> listeners = new ArrayList<>();
 private volatile double temp;
 protected TemperatureServerImplBS() throws RemoteException
 {
 //Default temperature
 temp = 88.00;
 }
@Override
 public void run()
 {
 Random lRandom = new Random();
 for (; ; )
 {
 int duration = lRandom.nextInt() % 10000 + 2000;
 if (duration < 0)
     {
 duration = duration * -1;
 }
 try {
 Thread.sleep(duration);
 }
 catch (InterruptedException aInE)
 {
 System.out.println(aInE.getMessage());
 }
 //Take a number to see if up or down
 int num = lRandom.nextInt();
 if (num < 0)
 {
 temp -= 0.5;
 }
 else
 {
 temp += 0.5;
 }
 notifyTemperatureListeners(temp);
 }
 }
  private void notifyTemperatureListeners(double aInTemp)
 {
 for (TemperaturelistenerBS lListener : listeners)
 {
 try
 { lListener.temperatureChanged(aInTemp); }
 catch (RemoteException aInE)
 {
 listeners.remove(lListener);
 }} }
 @Override
 public void addTemperatureListener(TemperaturelistenerBS temperatureListener) throws
RemoteException
 {
 listeners.add(temperatureListener);
 }
 @Override
 public void removeTemperatureListener(TemperaturelistenerBS temperatureListener) throws
RemoteException
 {
 listeners.remove(temperatureListener);
 }
 @Override
 public Double getTemperature() throws RemoteException
 {
 return temp;
 }
  public static void main(String[] args)
 {
 try
 {
 TemperatureServerImplBS lServer = new TemperatureServerImplBS();
 // Binding the remote object (stub) in the registry
 Registry reg = LocateRegistry.createRegistry(52369);
 String url = "rmi://" + InetAddress.getLocalHost().getHostAddress() + ":52369/Hello";
 reg.rebind(url, lServer);
 //Create the thread and change the temperature
 Thread lThread = new Thread(lServer);
 lThread.start();
 }
 catch (Exception aInE)
 {
 System.out.println("Remote error- " + aInE);
 }
 }
 }