Читаем Программирование на Java полностью

Важно подчеркнуть, что после установления соединения с клиентом сервер выходит из метода accept(), то есть перестает быть готовым принимать новые запросы. Однако, как правило, желательно, чтобы сервер мог работать с несколькими клиентами одновременно. Для этого необходимо при подключении очередного пользователя создавать новый поток исполнения, который будет обслуживать его, а основной поток снова войдет в метод accept(). Приведем пример такого решения:


import java.io.*; import java.net.*; public class NetServer { public static final int PORT = 2500; private static final int TIME_SEND_SLEEP = 100; private static final int COUNT_TO_SEND = 10; private ServerSocket servSocket; public static void main(String[] args) { NetServer server = new NetServer(); server.go(); } public NetServer() { try{ servSocket = new ServerSocket(PORT); } catch(IOException e) { System.err.println("Unable to open Server Socket : " + e.toString()); } } public void go() { // Класс-поток для работы с //подключившимся клиентом class Listener implements Runnable { Socket socket; public Listener(Socket aSocket) { socket = aSocket; } public void run() { try { System.out.println("Listener started"); int count = 0; OutputStream out = socket.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out); PrintWriter pWriter = new PrintWriter(writer); while (count1)?",":"")+ "Say" + count); sleeps(TIME_SEND_SLEEP); } pWriter.close(); } catch(IOException e) { System.err.println("Exception : " + e.toString()); } } } // Основной поток, циклически выполняющий метод accept() System.out.println("Server started"); while (true) { try { Socket socket = servSocket.accept(); Listener listener = new Listener(socket); Thread thread = new Thread(listener); thread.start(); } catch(IOException e) { System.err.println("IOException : " + e.toString()); } } } public void sleeps(long time) { try { Thread.sleep(time); } catch(InterruptedException e) { } } } Пример 16.2.

Теперь объявим клиента. Эта программа будет запускать несколько потоков, каждый из которых независимо подключается к серверу, считывает его ответ и выводит на консоль.


import java.io.*; import java.net.*; public class NetClient implements Runnable { public static final int PORT = 2500; public static final String HOST = "localhost"; public static final int CLIENTS_COUNT = 5; public static final int READ_BUFFER_SIZE = 10; private String name = null; public static void main(String[] args) { String name = "name"; for (int i=1; i<=CLIENTS_COUNT; i++) { NetClient client = new NetClient(name+i); Thread thread = new Thread(client); thread.start(); } } public NetClient(String name) { this.name = name; } public void run() { char[] readed = new char[READ_BUFFER_SIZE]; StringBuffer strBuff = new StringBuffer(); try { Socket socket = new Socket(HOST, PORT); InputStream in = socket.getInputStream(); InputStreamReader reader = new InputStreamReader(in); while (true) { int count = reader.read(readed, 0, READ_BUFFER_SIZE); if (count==-1) break; strBuff.append(readed, 0, count); Thread.yield(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("client " + name + " read : " + strBuff.toString()); } } Пример 16.3.

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных
1001 совет по обустройству компьютера
1001 совет по обустройству компьютера

В книге собраны и обобщены советы по решению различных проблем, которые рано или поздно возникают при эксплуатации как экономичных нетбуков, так и современных настольных моделей. Все приведенные рецепты опробованы на практике и разбиты по темам: аппаратные средства персональных компьютеров, компьютерные сети и подключение к Интернету, установка, настройка и ремонт ОС Windows, работа в Интернете, защита от вирусов. Рассмотрены не только готовые решения внезапно возникающих проблем, но и ответы на многие вопросы, которые возникают еще до покупки компьютера. Приведен необходимый минимум технических сведений, позволяющий принять осознанное решение.Компакт-диск прилагается только к печатному изданию книги.

Юрий Всеволодович Ревич

Программирование, программы, базы данных / Интернет / Компьютерное «железо» / ОС и Сети / Программное обеспечение / Книги по IT