📄 server.java
字号:
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.rmi.registry.*;
public class Server extends UnicastRemoteObject implements Serverinterface{
private static Semaphore semaphore=new Semaphore(1); // to make the syncronized update
// vector for store list of callback objects
private static Vector callbackObjects;
private static int count1=0; //record the number of "yes"
private static int count2=0; //record the number of "no"
private static int count3=0; //record the number of "do not care"
public Server() throws RemoteException {
super();
// instantiate a Vector object for storing callback objects
callbackObjects = new Vector();
}
// do recording
public void update(String m){
try {
semaphore.acquire();
if(m.equals("1")) this.count1++;
if(m.equals("2")) this.count2++;
if(m.equals("3")) this.count3++;
}
catch(InterruptedException ex){
}
finally{
semaphore.release();
}
}
// method for client to call to add itself to its callback
public void addCallback(Callbackinterface CallbackObject) {
// store the callback object into the vector
System.out.println("Server got an 'addCallback' call.");
callbackObjects.addElement (CallbackObject);
}
private static void startRegistry(int RMIPortNum)
throws RemoteException{
try {
Registry registry= LocateRegistry.getRegistry(RMIPortNum);
registry.list( );
// The above call will throw an exception
// if the registry does not already exist
}
catch (RemoteException ex) {
// No valid registry at that port.
System.out.println(
"RMI registry cannot be located at port " + RMIPortNum);
Registry registry= LocateRegistry.createRegistry(RMIPortNum);
System.out.println( "RMI registry created at port " + RMIPortNum);
}
} // end startRegistry
private static void callback( ) {
// the server calls the clients in the list
for (int i = 0; i < callbackObjects.size(); i++) {
System.out.println("Now performing the "+ i +"th callback\n");
// convert the vector object to a callback object
Callbackinterface client =
(Callbackinterface) callbackObjects.elementAt(i);
try{
client.callMe ( "Server calling back to client " + i);
}
catch(Exception ex){
}
}
}//end callback
public static void main(String args[]) {
try{
Serverinterface obj = new Server();
startRegistry(1099);
Registry registry = LocateRegistry.getRegistry();
registry.rebind("Server", obj);
System.out.println("Server " + obj + " registered");
// callback( );
}
catch(Exception ex){
ex.printStackTrace();
}
} // end main
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -