Question about Computers & Internet

1 Answer

Please explain the working of this code

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();
}
}




















Posted by on

1 Answer

  • Level 1:

    An expert who has achieved level 1.

  • Contributor
  • 2 Answers

It's a Java http server (webserver) that serves random "prices" if they match a search string.

Well here is an explaination:

private static String[] symbols = {"DELL", "INTC", "MSFT", "ORCL", "SUNW"};
These are search strings

private static Random rnd = new Random();
This generates a random number

private static Charset cs = Charset.forName("UTF-8");
This is the charset that the http server uses

ServerSocketChannel server = ServerSocketChannel.open();
Create a new server

server.socket().bind(new InetSocketAddress(8055));
Bind the http server to port 8055

The rest is handling the request and processing it

But here:
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 "));
channel.write(cs.encode("Content-type: text/plain "));
channel.write(cs.encode(response));
channel.close();
}
It sees if the string input matchs: DELL INTC MSFT ORCL SUNW.

(private static String[] symbols = {"DELL", "INTC", "MSFT", "ORCL", "SUNW"};)
If so, it gives a price based on a random number.
(
response = "Price is " + (1000 + rnd.nextInt(9000)) / 100.0;)
Or else
It says "price not available"
then it gives a html header to end the error message.

Hope I helped you :)
Gook luck

Posted on Nov 26, 2008

1 Suggested Answer

6ya6ya
  • 2 Answers

SOURCE: I have freestanding Series 8 dishwasher. Lately during the filling cycle water hammer is occurring. How can this be resolved

Hi,
a 6ya expert can help you resolve that issue over the phone in a minute or two.
best thing about this new service is that you are never placed on hold and get to talk to real repairmen in the US.
the service is completely free and covers almost anything you can think of (from cars to computers, handyman, and even drones).
click here to download the app (for users in the US for now) and get all the help you need.
goodluck!

Posted on Jan 02, 2017

Add Your Answer

Uploading: 0%

my-video-file.mp4

Complete. Click "Add" to insert your video. Add

×

Loading...
Loading...

Related Questions:

2 Answers

Codes for if else if statement in java script


if (condition) {
//conditional true code here
} else {
//conditional false code here
}

Mar 23, 2011 | Computers & Internet

1 Answer

Which language is best for project,java or .net


JAVA = Old Skool...... Dot Net, is Hip, Now.... Java.. works, sometimes, Dot Net, work, works most times.

May 05, 2010 | Project Delta

1 Answer

I need a complete workingsource code written in


This is a simple source code for Simple calculator in Java using RMI
//mathServer//
import java.rmi.*;
import java.rmi.Naming.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.net.*;
import java.util.*;
interface mathInterface extends Remote
{
public int add(int a,int b) throws RemoteException;
public int subt(int a,int b) throws RemoteException;
public int mult(int a,int b) throws RemoteException;
public int div(int a,int b) throws RemoteException;
}
public class mathServer extends UnicastRemoteObject implements
mathInterface
{
public mathServer() throws RemoteException
{
System.out.println("Initializing Server");
}
public int add(int a,int b)
{
return(a+b);
}
public int subt(int a,int b)
{
return(a-b);
}
public int mult(int a,int b)
{
return(a*b);
}
public int div(int a,int b)
{
return(a/b);
}
public static void main(String args[])
{
try
{
mathServer ms=new mathServer();
java.rmi.Naming.rebind("MathServ",ms);
System.out.println("Server Ready");
}
catch(RemoteException RE)
{
System.out.println("Remote Server Error:"+ RE.getMessage());
System.exit(0);
}
catch(MalformedURLException ME)
{
System.out.println("Invalid URL!!");
}
}
}

//mathClient//
import java.rmi.*;
import java.rmi.registry.*;
import java.awt.*;
import java.awt.event.*;
public class mathClient extends Frame implements ActionListener
{
Button B1=new Button("Sum");
Button B2=new Button("Subtract");
Button B3=new Button("Multiply");
Button B4=new Button("Divide");
Label l1=new Label("Number 1");
Label l2=new Label("Number 2");
Label l3=new Label("Result");
TextField t1=new TextField(20);
TextField t2=new TextField(20);
TextField t3=new TextField(20);
public mathClient()
{
super("Calculator");
setLayout(null);
l1.setBounds(20,50,55,25);
add(l1);
l2.setBounds(20,100,55,25);
add(l2);
l3.setBounds(20,150,55,25);
add(l3);
t1.setBounds(150,50,100,25);
add(t1);
t2.setBounds(150,100,100,25);
add(t2);
t3.setBounds(150,150,100,25);
add(t3);
B1.setBounds(20,200,80,25);
add(B1);
B2.setBounds(100,200,80,25);
add(B2);
B3.setBounds(180,200,80,25);
add(B3);
B4.setBounds(260,200,80,25);
add(B4);
B1.addActionListener(this);
B2.addActionListener(this);
B3.addActionListener(this);
B4.addActionListener(this);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent AE)
{
if(AE.getSource()==B1)
{
sum();
}
else if(AE.getSource()==B2)
{
subt();
}
else if(AE.getSource()==B3)
{
mult();
}
else if(AE.getSource()==B4)
{
div();
}
}
public void sum()
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int val;
try
{
String ServerURL="MathServ";
mathInterface MI=(mathInterface)Naming.lookup(ServerURL);
val=MI.add(i,j);
t3.setText(""+val);
}
catch(Exception ex)
{
System.out.println("Exception:"+ex);
}
}
public void subt()
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int val;
try
{
String ServerURL="MathServ";
mathInterface MI=(mathInterface)Naming.lookup(ServerURL);
val=MI.subt(i,j);
t3.setText(""+val);
}
catch(Exception ex)
{
System.out.println("Exception:"+ex);
}
}
public void mult()
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int val;
try
{
String ServerURL="MathServ";
mathInterface MI=(mathInterface)Naming.lookup(ServerURL);
val=MI.mult(i,j);
t3.setText(""+val);
}
catch(Exception ex)
{
System.out.println("Exception:"+ex);
}
}
public void div()
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int val;
try
{
String ServerURL="MathServ";
mathInterface MI=(mathInterface)Naming.lookup(ServerURL);
val=MI.div(i,j);
t3.setText(""+val);
}
catch(Exception ex)
{
System.out.println("Exception:"+ex);
}
}
public static void main(String args[])
{
mathClient MC=new mathClient();
MC.setVisible(true);
MC.setSize(600,500);
};
}

Jul 03, 2009 | Microsoft Computers & Internet

1 Answer

I want to read text file which is located in c drive using java code can anybody help me out


import java.io.*;
import java.util.Scanner;

public final class ReadWithScanner { public static void main(String... aArgs) throws FileNotFoundException {
ReadWithScanner parser = new ReadWithScanner("C:\\Temp\\test.txt");
parser.processLineByLine();
log("Done.");
}

/**
* @param aFileName full name of an existing, readable file.
*/

public ReadWithScanner(String aFileName){
fFile = new File(aFileName);
}

/** Template method that calls {@link #processLine(String)}. */
public final void processLineByLine() throws FileNotFoundException {
Scanner scanner = new Scanner(fFile);
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
//ensure the underlying stream is always closed
scanner.close();
}
}

/**
* Overridable method for processing lines in different ways.
*
* <P>This simple default implementation expects simple name-value pairs, separated by an
* '=' sign. Examples of valid input :
* <tt>height = 167cm</tt>
* <tt>mass = 65kg</tt>
* <tt>disposition = "grumpy"</tt>
* <tt>this is the name = this is the value</tt>
*/

protected void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if ( scanner.hasNext() ){
String name = scanner.next();
String value = scanner.next();
log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
//(no need for finally here, since String is source)
scanner.close();
}

// PRIVATE //
private final File fFile;

private static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}

private String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}

Jun 22, 2009 | Sun Java Programming Language (cdj-275)

2 Answers

Rename a folder in c drive using java code


import java.io.*;

public class RenameFileOrDir{

public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the file or directory
name which has to be Renamed : ");

String old_name = in.readLine();
File oldfile = new File(old_name);


if(!oldfile.exists())
{

System.out.println("File or directory does not exist.");

System.exit(0);

}

System.out.print("please enter the new file or directory name : ");

String new_name = in.readLine();

File newfile = new File(new_name);

System.out.println("Old File or directory name : "+ oldfile);
System.out.println("New File or directory name : "+ newfile);
boolean Rename = oldfile.renameTo(newfile);

if(!Rename)
{

System.out.println("File or directory does not rename successfully.");

System.exit(0);

}

else {

System.out.println("File or directory rename is successfully.");

}

}

}

Mar 30, 2009 | Sun Java Programming Language (cdj-275)

1 Answer

How to play audio clip in java


  • Create an AudioClip object
  • Load .au sound file into AudioClip
  • Play sounds once or loop continuously
  • Stop playback


Here's how the code for these steps looks:
import java.applet.*;
AudioClip ac = getAudioClip(getCodeBase(), soundFile);
ac.play(); //play once
ac.stop(); //stop playing
ac.loop(); //play continuously


It would seem logical to use this same code to play audio clips in a Java application. Unfortunately, if you do that you will get errors from the compiler. Why? Because the AudioClip object and the getAudioClip() method are part of the java.applet package -- and are not part of applications. The good news is we can dive down and make things work ourselves.
The trick to solving this problem is to use some undocumented features that are provided by Sun in its JDK. Taking a peek inside the classes.zip file from the Sun JDK (using any of the various zipfile utilities), we find not only the standard Java packages such as java.applet but also sun.audio. (These are in the directory sun/audio.)
The sun.audio package contains everything we need to be able to play audio clips! Here's the code:
import sun.audio.*; //import the sun.audio package
import java.io.*;
//** add this into your application code as appropriate
// Open an input stream to the audio file.
InputStream in = new FileInputStream(Filename);
// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);
// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);
// Similarly, to stop the audio.
AudioPlayer.player.stop(as);


To use a URL as the audio stream source, substitute the following for the input stream and audio stream setup:
AudioStream as = new AudioStream (url.openStream());


Playing the audio stream continuously adds a bit more complexity:
// Create audio stream as discussed previously.
// Create AudioData source.
AudioData data = as.getData();
// Create ContinuousAudioDataStream.
ContinuousAudioDataStream cas = new ContinuousAudioDataStream (data);
// Play audio.
AudioPlayer.player.play (cas);
// Similarly, to stop the audio.
AudioPlayer.player.stop (cas);

Jan 22, 2009 | Computers & Internet

1 Answer

Java


UNINSTALL your old version of Java, then Install the updated version, - this works, in that order....

Dec 26, 2007 | Computers & Internet

11 Answers

How to upload JAVA applications ?


First you have to find compatible java games for your phone. you can find free ones on this link http://www.getjar.com/ 1- upload jar and jad files to your phone 2- *#9998*5282# enter this code 3- select İnstall MIDlet 4- enter password 235282 5- on next menu you have to see your jar and jad files select jad file 6- select install 7- after installing the game you can find the game in applications/java games

Jul 23, 2007 | Samsung SGH-E900 Cellular Phone

Not finding what you are looking for?
Computers & Internet Logo

Related Topics:

148 people viewed this question

Ask a Question

Usually answered in minutes!

Top Computers & Internet Experts

Brian Sullivan
Brian Sullivan

Level 3 Expert

27725 Answers

kakima

Level 3 Expert

98868 Answers

David Payne
David Payne

Level 3 Expert

14088 Answers

Are you a Computer and Internet Expert? Answer questions, earn points and help others

Answer questions

Manuals & User Guides

Loading...