/**
* This program is an example from the book "Internet
* programming with Java" by Svetlin Nakov. It is freeware.
* For more information: http://www.nakov.com/books/inetjava/
*/
import java.io.*;
import java.net.*;
import java.util.*;
public class StockQuoteServer {
public static int PORT = 2004;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket socket = serverSocket.accept();
StockQuoteThread clientThread =
new StockQuoteThread(socket);
clientThread.start();
}
}
}
class StockQuoteThread extends Thread {
private Socket mSocket;
private BufferedReader mSocketReader;
private PrintWriter mSocketWriter;
private Random mRandomGenerator = new Random();
public StockQuoteThread(Socket aSocket) throws IOException {
mSocket = aSocket;
mSocketReader = new BufferedReader(
new InputStreamReader(mSocket.getInputStream()));
mSocketWriter = new PrintWriter(
new OutputStreamWriter(mSocket.getOutputStream()));
}
public void run() {
try {
String companyTicker = mSocketReader.readLine();
while (!isInterrupted()) {
String quote = companyTicker + ": " +
getDate() + " " + getRandomQuote();
mSocketWriter.println(quote);
mSocketWriter.flush();
int delay = mRandomGenerator.nextInt(3000);
Thread.sleep(delay);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private String getRandomQuote() {
int value = mRandomGenerator.nextInt(10000);
return " " + (value / 100) + "." + value % 100;
}
private String getDate() {
return (new Date()).toString();
}
}
Back to Internet
Programming with Java books's web site