-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelloServer.java
More file actions
55 lines (43 loc) · 1.78 KB
/
HelloServer.java
File metadata and controls
55 lines (43 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// HelloServer.java
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;
public class HelloServer implements HelloInterface {
// Store messages received from clients
private List<String> messages = new ArrayList<>();
// Implement the remote methods
public String sayHello(String name) throws RemoteException {
return "Hello, " + name + "!";
}
public int add(int a, int b) throws RemoteException {
return a + b;
}
// Client sends a message to server
public void sendMessage(String message) throws RemoteException {
messages.add(message);
System.out.println("Received from client: " + message);
}
// Get all messages stored on server
public List<String> getAllMessages() throws RemoteException {
return new ArrayList<>(messages);
}
public static void main(String[] args) {
try {
// Create an instance of the server
HelloServer server = new HelloServer();
// Export the remote object
HelloInterface stub = (HelloInterface) UnicastRemoteObject.exportObject(server, 0);
// Create or get the RMI registry on port 1099
Registry registry = LocateRegistry.createRegistry(1099);
// Bind the remote object to the registry
registry.rebind("HelloService", stub);
System.out.println("Server is ready and running on port 1099...");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}