import java.net.*; import java.io.*; import java.util.*;
public class NameServer {
NameTable table;
public NameServer() {
table = new NameTable();
}
void handleclient(Socket theClient) {
try {
BufferedReader din = new BufferedReader
(new InputStreamReader(theClient.getInputStream()));
PrintWriter pout = new PrintWriter(theClient.getOutputStream());
String command = din.readLine();
System.out.println("received:" + command);
StringTokenizer st = new StringTokenizer(command);
String tag = st.nextToken();
if (tag.equals("search")) {
InetSocketAddress entry = table.search(st.nextToken());
if (entry == null) pout.println(0 + " " + "nullhost");
else pout.println(entry.getPort() + " " + entry.getHostName());
} else if (tag.equals("insert")) {
String name = st.nextToken();
String hostName = st.nextToken();
int port = Integer.parseInt(st.nextToken());
int retValue = table.insert(name, hostName, port);
pout.println(retValue);
} else if (tag.equals("clear")) {
table.clear();
}
pout.flush();
} catch (IOException e) {
System.err.println(e);
}
}
public static void main(String[] args) {
NameServer ns = new NameServer();
System.out.println("NameServer started:");
try {
ServerSocket listener = new ServerSocket(Symbols.ServerPort);
while (true) {
Socket aClient = listener.accept();
ns.handleclient(aClient);
aClient.close();
}
} catch (IOException e) {
System.err.println("Server aborted:" + e);
}
}
}