Модераторы: Poseidon
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> [Java] Помогите написать чат! 
:(
    Опции темы
vitjoknew
Дата 5.3.2013, 00:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 1
Регистрация: 4.3.2013

Репутация: нет
Всего: нет



The GUI App is provided for you in the ChatFrame, your task is to
integrate a client and server applications based on Sockets. You need 
to create two classes for a Peer-To-Peer application.
For a Peer-To-Peer app:

    Create a PeerToPeerServer class file:

        - the Server class must implement the ActionListener interface
          to execute actions on button click

        - create the following fields:
            * a ServerSocket for the server
            * a Socket for the client
            * a PrintWriter for writing to the client
            * a BufferedReader for reader from the client
            * a ChatFrame for the GUI
            * an int variable for the port number
            * an int variable maxClients for storing the maximum number of clients
            

        - you will need to create the following methods to execute a PeerToPeerServer app:
            * a class constructor
                - you will need to instantiate the given ChatFrame class
                  to create the GUI of the app
                - use the 'void setButtonActionListener(ActionListener buttonActionListener)'
                  method  of the ChatFrame instance and pass it the current
                  instance, by using the 'this' keyword, to set the
                  default button clicked action
                - call the 'void startServer()' method to start the server

            * 'String receiveMessage()' that returns a String
              for handling the input from the client
                - in the method you will have to read input from the
                  accepted client, by using the readLine() method 
                  of the BufferedReader instance and return it 
                  
            * 'void acceptClient()'
                     - create an instance of the Socket by using the ServerSocket's method accept() that
                          return the client instance
               - create an instance of InputStreamReader and pass the clients input stream
                 to it's constructor, by using the clients getInputStream() method,
                 then instantiate the BufferedReader using the InputStreamReader 
                 instance by passing it to the constructor
               - instantiate the PrintWriter by using the clients OutputStream,
                 use the PrintWriter constructor with the boolean (autoflush) set to 'true' 
             
          * 'void processInputFromClientForever()'
               - create an infinite loop by using the while() loop with 'true':
                    - check if the client has been disconnected, to accept an another one
                      by using the client instances isConnected() method, and if it is 'false',
                      then call the 'void acceptClient()' method
                    - get the message from the client by using the
                      'String receiveMessage()' method and print it out using the 
                      chatFram instances printTextToScreen() method
               
           
            * 'void startServer()' for starting the server
               - instantiate the ServerSocket, using it's ServerSocket(int, int) constructor,
                 passing it the port variable and maxClients variable
                 catch all the Exceptions
               - call the 'void acceptClient()' method
               - call the 'void processInputFromClientForever()' method to process
                 clients input forever
               - don't forget to use try{} catch() {} finally {} to catch any exceptions occurring

           
            * 'void sendMessage(String message)' that accepts a String as input
              for handling the output to the client
                - in the method you will have to print the message to the screen
                  by using the 'void printTextToScreen(String text)' method of
                  the ChatFrame class
                - then you will have to send the message to the client
                  by using the println(String text) method of the PrintWriter, but
                  the outputToClient could be closed, so first check if it does not
                  equal to null

            * override the 'void actionPerformed(ActionEvent e)' method to implement the action that is triggered
              when the button is clicked
                - in the method use the 'String getMessageText()' of the ChatFrame
                  instance to get the text from the text field 
                - input the text from the text field to the
                  'void sendMessage(String message)' method,
                  to send a message to the client
                  
            * create a main method to run the server
                - create an instance of PeerToPeerServer
                   
    Create a Client class file:

        - the Client class must implement the ActionListener interface
          to execute actions on button click

        - create the following fields:

             * ChatFrame chatFrame for the GUI
             * int serverPort, that should be the same as the server port
             * Socket socketToServer, 
             * BufferedReader outputFromServer
             * PrintWriter inputToServer


        - you will need to create the following methods to execute a Client app:


            * 'void processInputFromServer()'
                - use an infinite while() loop and the BufferedReader instances 
                  readLine() method to read messages from the server 
                - use the ChatFrame instances 'void printTextToScreen(String text)'
                  method to print the message from the server to the screen
                  
            * a class constructor
                - you will need to instantiate the given ChatFrame class
                  to create the GUI of the app
                - use the 'void setButtonActionListener(ActionListener buttonActionListener)'
                  method  of the ChatFrame instance and pass it the current
                  instance, by using the 'this' keyword, to set the
                  default button clicked action
                - create a connection to the server by creating the Socket instance
                  and passing it the InetAddress.getLocalHost() if you're testing locally,
                  or the correct ip if testing from different hosts,
                  and the server port number (same as defined in the server class)
                - create an output stream to the server by instantiating the
                  PrintWriter and passing it the sockets output stream,
                  by using the getOutputStream() method, use the PrintWriter constructor
                  with the boolean (autoflush) set to true
                - create an input stream to the server by instantiating the
                  BufferedReader instance and passing it a new InputStreamReader
                  instance, with the socket input stream in it's constructor
                - call the 'void processInputFromServer()' method to start
                  processing input

            * 'void sendMessage(String message)'
                - use the PrintWriter instances println(String text) method
                  to write the message to the server,
                - use the printTextToScreen(String) method of the chatFrame
                  to print out your sent message to the screen

        
                
            * override the 'void actionPerformed(ActionEvent e)' method to implement the action that is triggered
              when the button is clicked
                - in the method use the 'String getMessageText()' of the ChatFrame
                  instance to get the text from the text field 
                - input the text from the text field to the
                  'void sendMessage(String message)' method,
                  to send a message to the client

PM MAIL   Вверх
Dummy
Дата 6.3.2013, 12:20 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 263
Регистрация: 21.5.2007

Репутация: нет
Всего: 19



Вы ожидаете, что кто-то придёт и напишет для Вас программу целиком?
PM MAIL   Вверх
jk1
Дата 9.3.2013, 19:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник
Сообщений: 1168
Регистрация: 17.10.2008
Где: Санкт-Петербург

Репутация: 1
Всего: 75



Для домашних заданий, курсовых, существует "Центр Помощи".

Тема перенесена! 


--------------------
Opinions are like assholes — everybody has one
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Центр помощи"

ВНИМАНИЕ! Прежде чем создавать темы, или писать сообщения в данный раздел, ознакомьтесь, пожалуйста, с Правилами форума и конкретно этого раздела.
Несоблюдение правил может повлечь за собой самые строгие меры от закрытия/удаления темы до бана пользователя!


  • Название темы должно отражать её суть! (Не следует добавлять туда слова "помогите", "срочно" и т.п.)
  • При создании темы, первым делом в квадратных скобках укажите область, из которой исходит вопрос (язык, дисциплина, диплом). Пример: [C++].
  • В названии темы не нужно указывать происхождение задачи (например "школьная задача", "задача из учебника" и т.п.), не нужно указывать ее сложность ("простая задача", "легкий вопрос" и т.п.). Все это можно писать в тексте самой задачи.
  • Если Вы ошиблись при вводе названия темы, отправьте письмо любому из модераторов раздела (через личные сообщения или report).
  • Для подсветки кода пользуйтесь тегами [code][/code] (выделяйте код и нажимаете на кнопку "Код"). Не забывайте выбирать при этом соответствующий язык.
  • Помните: один топик - один вопрос!
  • В данном разделе запрещено поднимать темы, т.е. при отсутствии ответов на Ваш вопрос добавлять новые ответы к теме, тем самым поднимая тему на верх списка.
  • Если вы хотите, чтобы вашу проблему решили при помощи определенного алгоритма, то не забудьте описать его!
  • Если вопрос решён, то воспользуйтесь ссылкой "Пометить как решённый", которая находится под кнопками создания темы или специальным флажком при ответе.

Более подробно с правилами данного раздела Вы можете ознакомится в этой теме.

Если Вам помогли и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, Poseidon, Rodman

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Центр помощи | Следующая тема »


 




[ Время генерации скрипта: 0.0470 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.