
February 22nd, 2008, 07:51 AM
|
|
Contributing User
|
|
Join Date: Jun 2007
Posts: 128
Time spent in forums: 2 Days 10 h 30 m 28 sec
Reputation Power: 2
|
|
|
New to Java Thread Help
Hello all. I'm working on my first Java program, which is a threaded server. I have everything working in the program except for the threading (the hard part). My understanding is that the bulk of my code should be in a run function, and my main should just wait for socket connections. I attempted to use one of the Runnable functions with no success. My code is posted below. As I said I think I have 95% of it, i just need the part that waits/starts multiple connections.
Thanks,
Code:
import java.net.*;
import java.io.*;
import java.util.Random;
public class server2
{
public static int fibonacci (int number)
{
if ( number == 0 || number == 1 )
return ( number );
else
return (fibonacci(number - 1) + fibonacci (number - 2));
}
public void main (String[] args)
{
int selection = -1;
int sock_choice = 7001;
int fib = -1;
int n = -1;
long time = -1;
String user_input;
try
{
ServerSocket sock = new ServerSocket (sock_choice);
// now listen for connections
while (true)
{
Socket client = sock.accept();
PrintWriter pout = new
PrintWriter(client.getOutputStream(), true);
pout.println("Make a selection from the menu: \r");
pout.println("1) Time and date \r");
pout.println("2) Random saying \r");
pout.println("3) Fibonacci sequence for n \r");
pout.println("4) Quit \r");
BufferedReader client_in =
new BufferedReader (new InputStreamReader(client.getInputStream()));
user_input = client_in.readLine();
selection = Integer.parseInt(user_input);
if (selection == 1)
{
pout.println(new java.util.Date() .toString());
// write the date to the socket
}
else if (selection == 2 )
{
pout.println("RANDOM STATEMENT HERE");
time = System.currentTimeMillis();
time = time % 10;
if (time <= 2 )
{
pout.println("With the lights out it's less dangerous \r");
}
else if (time > 2 && time <= 5)
{
pout.println("God is in the TV \r");
}
else if (time > 5 && time <= 8)
{
pout.println("I never thought I would say this, I want to program in C++ \r");
}
else
{
pout.println("Your random number is greater than 8, couldn't think of anything else \r");
}
}
else if (selection == 3)
{
pout.println("FIBONACCI SEQUENCE HERE \r");
pout.println ("ENTER A NUMBER TO DISPLAY THE FIBONACCI SEQUENCE \r");
BufferedReader client_in2 =
new BufferedReader (new InputStreamReader(client.getInputStream()));
user_input = client_in2.readLine();
n = Integer.parseInt(user_input);
int x= fibonacci(n);
{
pout.println("The Fibonacci of \r"); pout.println( n ); pout.println ("is \r"); pout.println( x );
}
}
else if (selection == 4)
{
pout.println("EXITING");
}
else
{
pout.println("MAKE A SELECTION FROM THE MENU");
}
client.close();
}
}
catch (IOException ioe)
{
System.err.println(ioe);
}
}
}
|