/**
* 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.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class DictionaryServer {
public static int LISTENING_PORT = 3333;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket =
new ServerSocket(LISTENING_PORT);
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
DictionaryClientThread dictionaryClientThread =
new DictionaryClientThread(socket);
dictionaryClientThread.start();
}
}
}
class DictionaryClientThread extends Thread {
private int CLIENT_REQUEST_TIMEOUT = 15*60*1000; // 15 min.
private Socket mSocket;
private BufferedReader mSocketReader;
private PrintWriter mSocketWriter;
public DictionaryClientThread(Socket aSocket)
throws IOException {
mSocket = aSocket;
mSocket.setSoTimeout(CLIENT_REQUEST_TIMEOUT);
mSocketReader = new BufferedReader(
new InputStreamReader(mSocket.getInputStream()));
mSocketWriter = new PrintWriter(
new OutputStreamWriter(mSocket.getOutputStream()));
}
public void run() {
System.out.println(new Date().toString() + " : " +
"Accepted client : " + mSocket.getInetAddress() +
":" + mSocket.getPort());
try {
mSocketWriter.println("Dictionary server ready.");
mSocketWriter.flush();
while (!isInterrupted()) {
String word = mSocketReader.readLine();
if (word == null)
break; // Client closed the socket
String translation = getTranslation(word);
mSocketWriter.println(translation);
mSocketWriter.flush();
}
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(new Date().toString() + " : " +
"Connection lost : " + mSocket.getInetAddress() +
":" + mSocket.getPort());
}
private String getTranslation(String aWord) {
if (aWord.equalsIgnoreCase("network")) {
return "мрежа";
} else if (aWord.equalsIgnoreCase("firewall")) {
return "защитна стена";
} else {
return "! непозната дума !";
}
}
}
Back to Internet
Programming with Java books's web site