Finger Server
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NewFingerServer {
private static void readPlan(String userName, PrintWriter pw) throws Exception {
FileReader file = new FileReader(userName + ".plan");
BufferedReader buff = new BufferedReader(file);
boolean eof = false;
pw.println("\nUser name: " + userName + "\n");
while (!eof) {
String line = buff.readLine();
if (line == null)
eof = true;
else
pw.println(line);
}
buff.close();
}
public static void main(String[] arguments) throws Exception {
ServerSocketChannel sockChannel = ServerSocketChannel.open();
sockChannel.configureBlocking(false);
InetSocketAddress server = new InetSocketAddress("localhost", 79);
ServerSocket socket = sockChannel.socket();
socket.bind(server);
Selector selector = Selector.open();
sockChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set keys = selector.selectedKeys();
Iterator it = keys.iterator();
while (it.hasNext()) {
SelectionKey selKey = (SelectionKey) it.next();
it.remove();
if (selKey.isAcceptable()) {
ServerSocketChannel selChannel = (ServerSocketChannel) selKey.channel();
ServerSocket selSocket = selChannel.socket();
Socket connection = selSocket.accept();
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader is = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()), false);
pw.println("NIO Finger Server");
pw.flush();
String outLine = null;
String inLine = is.readLine();
if (inLine.length() > 0) {
outLine = inLine;
}
readPlan(outLine, pw);
pw.flush();
pw.close();
is.close();
connection.close();
}
}
}
}
}
Related examples in the same category