⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lightbulbservant.java

📁 Java网络编程与分布式计算, 主要分析java网络各方面的编程, 提供许多实用安全
💻 JAVA
字号:
import java.util.Random;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;

// Chapter 12, Listing 1
public class LightBulbServant extends _LightBulbImplBase
{
	// Boolean flag representing light bulb state
	private boolean bulbOn;

	// Boolean flag representing light bulb working
	private boolean bulbOk = true;

	public LightBulbServant()
	{
		// Off by default
		bulbOn = false;
	}

	// Implementing operations defined by the LightBulb interface
	// Remember, the Operations class of any interface contains
	// the Java method signatures you must implement.

	// Turn on the bulb
	public void on () throws BulbBrokenException
	{
		// Check to see if bulb already on
		if (bulbOn)
			return;

		// Check to see if bulb broken
		if (!bulbOk)
			throw new BulbBrokenException();

		// Check to see if bulb will break
		Random r = new Random();

		// Make it a one in four chance, since it is an old bulb
		// and we want to test the throwing of an exception
		int chance = r.nextInt() % 4;

		if ( chance == 0)
		{
			bulbOk = false;
			bulbOn = false;
			throw new BulbBrokenException();
		}
		else
		{
			bulbOn = true;
		}
	}

	// Turn off the bulb
	public void off ()
	{		
		bulbOn = false;
	}

	// Is the bulb on and working?
	public boolean isOn () throws BulbBrokenException
	{
		// Check to see if broken
		if ( !bulbOk )
			throw new BulbBrokenException();

		// Return bulb state
		return bulbOn;		
	}

	public static void main(String args[])
	{
		System.out.println ("Loading ORB");

		try
		{

			// Create the ORB
			ORB orb = ORB.init(args, null);

			// Create a new light bulb servant ...
			LightBulbServant servant = new LightBulbServant();

			// ... and connect it to our orb
			orb.connect(servant);

			// Object Request Broker ready
			System.out.println ("Light bulb service loaded");

			// Next step : export the orb to our name service

			// Get a name service reference
			org.omg.CORBA.Object object = 
			orb.resolve_initial_references("NameService");

			// Narrow to a NamingContext object
			NamingContext namingContext = 
				NamingContextHelper.narrow(object);

			// Creating a naming component for our servant
			NameComponent component =
				new NameComponent ("LightBulb", "");

			// NamingContext requires an array, not a single
			// NameComponent
			NameComponent componentList[] = { component };

			// Now notify naming service of our new interface
			namingContext.rebind(componentList, servant);

			System.out.println ("Servant registered");

			// Wait indefinitely for clients to use the servant
			for (;;)
			{
			}
		}
		catch (Exception e)
		{
			System.err.println ("Error - " + e);
		}

	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -