Question:

Please explain the working of this code

by  |  earlier

0 LIKES UnLike

import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
class NewIOHTTPServerTest{
private static String[] symbols = {"DELL", "INTC", "MSFT", "ORCL", "SUNW"};
private static Random rnd = new Random();
private static Charset cs = Charset.forName("UTF-8");
public static void main(String[] args) throws Exception{
Selector selector = Selector.open();

ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new InetSocketAddress(8055));
server.register(selector, SelectionKey.OP_ACCEPT);

//register other server channels

for(;;){
if(selector.select(1000) > 0){
Iterator i = selector.selectedKeys().iterator();
while(i.hasNext()){
SelectionKey key = (SelectionKey) i.next();
if(key.isAcceptable()){
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel client = channel.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}else if(key.isReadable()){
SocketChannel channel = (SocketChannel) key.channel();
if(channel.socket().getLocalPort() == 8055)
handleHTTPRequest(channel);
}
i.remove();
}
}else{
System.out.print(new Date() + "\r");
}
}
}
private static void handleHTTPRequest(SocketChannel channel) throws IOException{
ByteBuffer buffer = ByteBuffer.allocate(1024);
int n = channel.read(buffer);
buffer.flip();
String request = cs.decode(buffer).toString();
String[] headers = request.split("\r\n");
String symbol = headers[0].substring(5, headers[0].length() - 9);
String response;
if(Arrays.binarySearch(symbols, symbol) >= 0)
response = "Price is " + (1000 + rnd.nextInt(9000)) / 100.0;
else
response = "Price not available";
channel.write(cs.encode("HTTP/1.0 200 OK\r\n"));
channel.write(cs.encode("Content-type: text/plain\r\n\r\n"));
channel.write(cs.encode(response));
channel.close();
}
}

 Tags:

   Report
Please Login to view 1 answers to this question

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.