Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Java sockets 101.pdf
Скачиваний:
22
Добавлен:
24.05.2014
Размер:
207.01 Кб
Скачать

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Code listing for PooledConnectionHandler

import java.io.*; import java.net.*; import java.util.*;

public class PooledConnectionHandler implements Runnable { protected Socket connection;

protected static List pool = new LinkedList(); public PooledConnectionHandler() {

}

public void handleConnection() { try {

PrintWriter streamWriter = new PrintWriter(connection.getOutputStream()); BufferedReader streamReader = new BufferedReader(new InputStreamReader(con String fileToRead = streamReader.readLine();

BufferedReader fileReader = new BufferedReader(new FileReader(fileToRead)) String line = null;

while ((line = fileReader.readLine()) != null) streamWriter.println(line);

fileReader.close();

streamWriter.close();

streamReader.close();

} catch (FileNotFoundException e) {

System.out.println("Could not find requested file on the server."); } catch (IOException e) {

System.out.println("Error handling a client: " + e);

}

}

public static void processRequest(Socket requestToHandle) { synchronized (pool) {

pool.add(pool.size(), requestToHandle); pool.notifyAll();

}

}

public void run() { while (true) {

synchronized (pool) {

while (pool.isEmpty()) { try {

pool.wait();

} catch (InterruptedException e) { return;

}

}

connection = (Socket) pool.remove(0);

}

handleConnection();

}

}

}

Colophon

This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial generator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLT extension functions that convert an XML file into a number of HTML pages, a zip file, JPEG heading graphics, and two PDF files. Our ability to generate multiple text and binary formats from a single source file illustrates the power and flexibility of XML. (It also saves our production team a great deal of time and effort.)

Java sockets 101

Page 37 of 38

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

You can get the source code for the Toot-O-Matic at www6.software.ibm.com/dl/devworks/dw-tootomatic-p. The tutorial Building tutorials with the Toot-O-Matic demonstrates how to use the Toot-O-Matic to create your own tutorials. developerWorks also hosts a forum devoted to the Toot-O-Matic; it's available at www-105.ibm.com/developerworks/xml_df.nsf/AllViewTemplate?OpenForm&RestrictToCategory=11. We'd love to know what you think about the tool.

Java sockets 101

Page 38 of 38