|
| 1 | + |
| 2 | +//In the name of our Lord Jesus Christ, when you are gathered together, and my spirit, with the power of our Lord Jesus Christ (1Cor 5:4) |
| 3 | + |
| 4 | +package com.javarush.task.task30.task3008.client; |
| 5 | + |
| 6 | +import java.io.IOException; |
| 7 | +import java.net.Socket; |
| 8 | +import com.javarush.task.task30.task3008.ConsoleHelper; |
| 9 | +import com.javarush.task.task30.task3008.Message; |
| 10 | +import com.javarush.task.task30.task3008.MessageType; |
| 11 | +import com.javarush.task.task30.task3008.Connection; |
| 12 | + |
| 13 | +public class Client { |
| 14 | + protected Connection connection; |
| 15 | + private volatile boolean clientConnected; |
| 16 | + |
| 17 | + public static void main(String[] args) { |
| 18 | + Client client = new Client(); |
| 19 | + client.run(); |
| 20 | + } |
| 21 | + |
| 22 | + public void run() { |
| 23 | + { |
| 24 | + SocketThread socketThread = getSocketThread(); |
| 25 | + socketThread.setDaemon(true); |
| 26 | + socketThread.start(); |
| 27 | + try { |
| 28 | + synchronized (this) { |
| 29 | + wait(); |
| 30 | + } |
| 31 | + } catch (InterruptedException e) { |
| 32 | + ConsoleHelper.writeMessage("Thread error"); |
| 33 | + System.exit(1); |
| 34 | + } |
| 35 | + if (clientConnected) { |
| 36 | + ConsoleHelper.writeMessage("Connection established. To quit, type 'exit'"); |
| 37 | + while (clientConnected) { |
| 38 | + String message = ConsoleHelper.readString(); |
| 39 | + if (message.equalsIgnoreCase("exit")) { |
| 40 | + break; |
| 41 | + } else { |
| 42 | + if (shouldSendTextFromConsole()) { |
| 43 | + sendTextMessage(message); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } else { |
| 48 | + ConsoleHelper.writeMessage("Error at client side"); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + protected String getServerAddress() { |
| 54 | + String serverAddress; |
| 55 | + ConsoleHelper.writeMessage("Enter server address: "); |
| 56 | + serverAddress = ConsoleHelper.readString(); |
| 57 | + return serverAddress; |
| 58 | + } |
| 59 | + |
| 60 | + protected int getServerPort() { |
| 61 | + ConsoleHelper.writeMessage("Enter server port: "); |
| 62 | + return ConsoleHelper.readInt(); |
| 63 | + } |
| 64 | + |
| 65 | + protected String getUserName() { |
| 66 | + ConsoleHelper.writeMessage("Enter User name: "); |
| 67 | + return ConsoleHelper.readString(); |
| 68 | + } |
| 69 | + |
| 70 | + protected boolean shouldSendTextFromConsole() { |
| 71 | + return true; |
| 72 | + } |
| 73 | + |
| 74 | + protected SocketThread getSocketThread() { |
| 75 | + return new SocketThread(); |
| 76 | + } |
| 77 | + |
| 78 | + protected void sendTextMessage(String text) { |
| 79 | + try { |
| 80 | + connection.send(new Message(MessageType.TEXT, text)); |
| 81 | + } catch (IOException e) { |
| 82 | + ConsoleHelper.writeMessage("Error, can't send your message..."); |
| 83 | + clientConnected = false; |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + public class SocketThread extends Thread { |
| 88 | + |
| 89 | + public void run() { |
| 90 | + String serverAddress = getServerAddress(); |
| 91 | + int serverPort = getServerPort(); |
| 92 | + try { |
| 93 | + Socket socket = new Socket(serverAddress,serverPort); |
| 94 | + connection = new Connection(socket); |
| 95 | + clientHandshake(); |
| 96 | + clientMainLoop(); |
| 97 | + |
| 98 | + } catch (IOException | ClassNotFoundException e) { |
| 99 | + notifyConnectionStatusChanged(false); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + protected void processIncomingMessage(String message) { |
| 104 | + ConsoleHelper.writeMessage(message); |
| 105 | + } |
| 106 | + |
| 107 | + protected void informAboutAddingNewUser(String userName) { |
| 108 | + ConsoleHelper.writeMessage("User " + userName + " joined to chat"); |
| 109 | + } |
| 110 | + |
| 111 | + protected void informAboutDeletingNewUser(String userName) { |
| 112 | + ConsoleHelper.writeMessage("User " + userName + " has left this chat"); |
| 113 | + } |
| 114 | + |
| 115 | + protected void notifyConnectionStatusChanged(boolean clientConnected) { |
| 116 | + synchronized (Client.this) { |
| 117 | + Client.this.clientConnected = clientConnected; |
| 118 | + Client.this.notify(); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + protected void clientHandshake() throws IOException, ClassNotFoundException { |
| 123 | + Message message; |
| 124 | + |
| 125 | + while (!clientConnected) { |
| 126 | + try { |
| 127 | + message = connection.receive(); |
| 128 | + } catch (ClassNotFoundException e) { |
| 129 | + throw new IOException("Unexpected MessageType"); |
| 130 | + } |
| 131 | + if (message.getType() == MessageType.NAME_REQUEST) { |
| 132 | + connection.send(new Message(MessageType.USER_NAME, getUserName())); |
| 133 | + } else { |
| 134 | + if (message.getType() == MessageType.NAME_ACCEPTED) {notifyConnectionStatusChanged(true);} |
| 135 | + else throw new IOException("Unexpected MessageType");} |
| 136 | + |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + protected void clientMainLoop() throws IOException, ClassNotFoundException { |
| 141 | + Message message; |
| 142 | + |
| 143 | + while (true) { |
| 144 | + |
| 145 | + try { |
| 146 | + message = connection.receive(); |
| 147 | + } catch (Exception e) { |
| 148 | + break; |
| 149 | + } |
| 150 | + if (message.getType() == MessageType.TEXT) processIncomingMessage(message.getData()); |
| 151 | + else { |
| 152 | + if (message.getType() == MessageType.USER_ADDED) informAboutAddingNewUser(message.getData()); |
| 153 | + else { |
| 154 | + if (message.getType() == MessageType.USER_REMOVED) informAboutDeletingNewUser(message.getData()); |
| 155 | + else break; |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + } |
| 160 | + throw new IOException("Unexpected MessageType"); |
| 161 | + |
| 162 | + } |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +/* |
| 167 | +Чат (17) |
| 168 | +Последний, но самый главный метод класса SocketThread – это метод void run(). Добавь его. Его реализация с учетом уже созданных методов выглядит очень просто. |
| 169 | +
|
| 170 | +Давай напишем ее: |
| 171 | +1) Запроси адрес и порт сервера с помощью методов getServerAddress() и getServerPort(). |
| 172 | +2) Создай новый объект класса java.net.Socket, используя данные, полученные в предыдущем пункте. |
| 173 | +3) Создай объект класса Connection, используя сокет из п.17.2. |
| 174 | +4) Вызови метод, реализующий «рукопожатие» клиента с сервером (clientHandshake()). |
| 175 | +5) Вызови метод, реализующий основной цикл обработки сообщений сервера. |
| 176 | +6) При возникновении исключений IOException или ClassNotFoundException сообщи главному потоку о проблеме, используя notifyConnectionStatusChanged и false в качестве параметра. |
| 177 | +
|
| 178 | +Клиент готов, можешь запустить сервер, несколько клиентов и проверить как все работает. |
| 179 | +
|
| 180 | +
|
| 181 | +Требования: |
| 182 | +1. В методе run должно быть установлено и сохранено в поле connection соединение с сервером (для получения адреса сервера и порта используй методы getServerAddress и getServerPort). |
| 183 | +2. В методе run должен быть вызван метод clientHandshake. |
| 184 | +3. В методе run должен быть вызван метод clientMainLoop. |
| 185 | +4. При возникновении исключений IOException или ClassNotFoundException в процессе работы метода run, должен быть вызван метод notifyConnectionStatusChanged с параметром false. |
| 186 | +5. Сигнатура метода run должна соответствовать условию задачи. |
| 187 | +*/ |
0 commit comments