Все делал по заданию , валидатор все принимал, щас запускаю и надо ввести строку и вылетает ошибка про то что не получается ввести число, при запуске окна, просит ввести адрес и порт ,я ввожу рандомные числа и просто пустое окно чата
код со всех классов прикреплю ниже, прошу найти ошибка,подсказать ,протестировать
class Conection
package com.javarush.task.task30.task3008;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketAddress;
//класс соединения между клиентом и сервером.
public class Connection implements Closeable {
private final Socket socket;
private final ObjectOutputStream out;
private final ObjectInputStream in;
public Connection(Socket socket) throws IOException {
this.socket = socket;
this.out = new ObjectOutputStream(socket.getOutputStream());
this.in = new ObjectInputStream(socket.getInputStream());
}
public void send(Message message) throws IOException {
synchronized (out) { // Отправить
out.writeObject(message);
}
}
public Message receive() throws IOException, ClassNotFoundException{
Message message;
synchronized (in){ // Получить
message = (Message) in.readObject();
}
return message;
}
public SocketAddress getRemoteSocketAddress(){
return socket.getRemoteSocketAddress();
}
@Override
public void close() throws IOException {
try {
out.close();
in.close();
socket.close();
}
catch (IOException a){
a.getStackTrace();
}
}
}
class ConsoleHelper
package com.javarush.task.task30.task3008;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//вспомогательный класс, для чтения или записи в консоль.
public class ConsoleHelper {
private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public static void writeMessage(String message){
System.out.println(message);
}
public static String readString() throws IOException {
String sms = null;
try {
sms = reader.readLine();
return sms;
} catch (IOException e) {
System.out.println("Произошла ошибка при попытке ввода текста. Попробуйте еще раз.");
sms = readString();
return sms;
}
}
//Метод readInt должен использовать метод readString для чтения с консоли.
//Метод readString должен перехватывать IOException, выводить сообщение о некорректном вводе и повторять считывание с консоли.
public static int readInt() throws IOException {
int num = 0;
try {
num = Integer.parseInt(readString());
} catch (NumberFormatException e) {
System.out.println("Произошла ошибка при попытке ввода числа. Попробуйте еще раз.");
num = Integer.parseInt(reader.readLine());
}
return num;
}
}
class Message
package com.javarush.task.task30.task3008;
import java.io.Serializable;
//класс, отвечающий за пересылаемые сообщения.
public class Message implements Serializable {
private final MessageType type; // тип сообщения
private final String data; // данные сообщения
public Message(MessageType type) {
this.type = type;
this.data = null;
}
public Message(MessageType type, String data) {
this.type = type;
this.data = data;
}
public MessageType getType() {
return type;
}
public String getData() {
return data;
}
}
class Server
{
private static Map<String, Connection> connectionMap = new ConcurrentHashMap<>();
private static class Handler extends Thread {
private Socket socket;
public Handler(Socket socket) {
this.socket = socket;
}
private String serverHandshake(Connection connection) throws IOException, ClassNotFoundException{
String userName;
Message answer;
Message polz = new Message(MessageType.NAME_REQUEST, "Введите имя");
do {
connection.send(polz);
answer = connection.receive();
userName = answer.getData();
}
while (answer.getType() != MessageType.USER_NAME || userName.isEmpty() || connectionMap.containsKey(userName));
connectionMap.put(userName, connection);
connection.send(new Message(MessageType.NAME_ACCEPTED, "Имя принято"));
return userName;
}
private void notifyUsers(Connection connection, String userName) throws IOException { // порверка на добавление поьзователей
for (String name : connectionMap.keySet()) {
if(!name.equalsIgnoreCase(userName))
connection.send(new Message(MessageType.USER_ADDED, name ));
}
}
private void serverMainLoop(Connection connection, String userName) throws IOException, ClassNotFoundException { // ОТправка сообщения серверу
while (true) {
Message message = connection.receive();
if (message.getType() == MessageType.TEXT) {
String sms = message.getData();
Server.sendBroadcastMessage(new Message(MessageType.TEXT, userName + ": " + sms));
}
else
ConsoleHelper.writeMessage("Тип сообщения неверный,введите текст");
}
}
public void run(){
ConsoleHelper.writeMessage("Установленно соединение"+ socket.getRemoteSocketAddress());
String name = null;
try (Connection connection = new Connection(socket)){
name = serverHandshake(connection);
sendBroadcastMessage(new Message(MessageType.USER_ADDED, name));
notifyUsers(connection, name);
serverMainLoop(connection, name);
} catch (IOException | ClassNotFoundException e) {
ConsoleHelper.writeMessage("Ошибка сервера");
}
finally {
if (name!= null){
connectionMap.remove(name);
sendBroadcastMessage(new Message(MessageType.USER_REMOVED, name));
}
}
ConsoleHelper.writeMessage("Увы,соединение потяряно");
}
}
public static void sendBroadcastMessage(Message message){
for (String s : connectionMap.keySet()){
try {
connectionMap.get(s).send(message);
} catch (IOException e) {
System.out.println("Увы сообщение не отправленно");
}
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(ConsoleHelper.readInt());
System.out.println("Сервер запущен");
try {
while (true) {
Socket socket = serverSocket.accept();
Handler handler = new Handler(socket);
handler.start();
}
}
catch (IOException e){
System.out.println("Произошла ошибка.");
serverSocket.close();
}
}
}
class BotClient
package com.javarush.task.task30.task3008.client;
import com.javarush.task.task30.task3008.ConsoleHelper;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class BotClient extends Client {
public static void main(String[] args) throws IOException {
BotClient botClient = new BotClient();
botClient.run();
}
public class BotSocketThread extends Client.SocketThread {
@Override
protected void clientMainLoop() throws IOException, ClassNotFoundException {
sendTextMessage("Привет чатику. Я бот. Понимаю команды: дата, день, месяц, год, время, час, минуты, секунды.");
super.clientMainLoop();
}
protected void processIncomingMessage(String message) {
ConsoleHelper.writeMessage(message);
if (message.contains(":")) {
String[] messages = message.split(": ");
SimpleDateFormat dateFormat = null;
if ("дата".equalsIgnoreCase(messages[1].trim())) {
dateFormat = new SimpleDateFormat("d.MM.YYYY");
} else if ("день".equalsIgnoreCase(messages[1].trim())) {
dateFormat = new SimpleDateFormat("d");
} else if ("месяц".equalsIgnoreCase(messages[1].trim())) {
dateFormat = new SimpleDateFormat("MMMM");
} else if ("год".equalsIgnoreCase(messages[1].trim())) {
dateFormat = new SimpleDateFormat("YYYY");
} else if ("время".equalsIgnoreCase(messages[1].trim())) {
dateFormat = new SimpleDateFormat("H:mm:ss");
} else if ("час".equalsIgnoreCase(messages[1].trim())) {
dateFormat = new SimpleDateFormat("H");
} else if ("минуты".equalsIgnoreCase(messages[1].trim())) {
dateFormat = new SimpleDateFormat("m");
} else if ("секунды".equalsIgnoreCase(messages[1].trim())) {
dateFormat = new SimpleDateFormat("s");
}
if (dateFormat != null) {
sendTextMessage("Информация для "
+ messages[0].trim()
+ ": "
+ dateFormat.format(Calendar.getInstance().getTime())
);
}
}
}
}
@Override
protected SocketThread getSocketThread() {
return new BotSocketThread();
}
@Override
protected boolean shouldSendTextFromConsole() {
return false;
}
@Override
protected String getUserName() {
return "date_bot_" + (int) (Math.random() * 100);
}
}
class Client
package com.javarush.task.task30.task3008.client;
import com.javarush.task.task30.task3008.Connection;
import com.javarush.task.task30.task3008.ConsoleHelper;
import com.javarush.task.task30.task3008.Message;
import com.javarush.task.task30.task3008.MessageType;
import java.io.IOException;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Client client = new Client();
client.run();
}
private volatile boolean clientConnected = false;
protected Connection connection;
public class SocketThread extends Thread {
protected void processIncomingMessage(String message) {
ConsoleHelper.writeMessage(message);
}
protected void informAboutAddingNewUser(String userName) {
ConsoleHelper.writeMessage("User " + userName + " is connected to the chat.");
}
protected void informAboutDeletingNewUser(String userName) {
ConsoleHelper.writeMessage("User " + userName + " left the chat.");
}
protected void notifyConnectionStatusChanged(boolean clientConnected) {
Client.this.clientConnected = clientConnected;
synchronized (Client.this) {
Client.this.notify();
}
}
protected void clientHandshake() throws IOException, ClassNotFoundException {
Message message;
while (true) {
message = connection.receive();
if (message.getType() == MessageType.NAME_REQUEST) {
String userName = getUserName();
connection.send(new Message(MessageType.USER_NAME, userName));
} else if (message.getType() == MessageType.NAME_ACCEPTED) {
notifyConnectionStatusChanged(true);
break;
} else {
throw new IOException("Unexpected MessageType");
}
}
}
protected void clientMainLoop() throws IOException, ClassNotFoundException {
Message message;
while (true) {
message = connection.receive();
if (message.getType() == MessageType.TEXT) {
processIncomingMessage(message.getData());
} else if (message.getType() == MessageType.USER_ADDED) {
informAboutAddingNewUser(message.getData());
} else if (message.getType() == MessageType.USER_REMOVED) {
informAboutDeletingNewUser(message.getData());
} else {
throw new IOException("Unexpected MessageType");
}
}
}
@Override
public void run() {
String address = null;
try {
address = getServerAddress();
} catch (IOException e) {
e.printStackTrace();
}
int port = 0;
try {
port = getServerPort();
} catch (IOException e) {
e.printStackTrace();
}
try {
Socket socket = new Socket(address, port);
connection = new Connection(socket);
clientHandshake();
clientMainLoop();
} catch (IOException | ClassNotFoundException e) {
notifyConnectionStatusChanged(false);
}
}
}
protected String getServerAddress() throws IOException {
return ConsoleHelper.readString();
}
protected int getServerPort() throws IOException {
return ConsoleHelper.readInt();
}
protected String getUserName() throws IOException {
return ConsoleHelper.readString();
}
protected boolean shouldSendTextFromConsole() {
return true;
}
protected SocketThread getSocketThread() {
return new SocketThread();
}
protected void sendTextMessage(String text) {
try {
connection.send(new Message(MessageType.TEXT, text));
} catch (IOException e) {
ConsoleHelper.writeMessage(e.getMessage());
clientConnected = false;
}
}
public void run() throws IOException {
SocketThread socketThread = getSocketThread();
socketThread.setDaemon(true);
socketThread.start();
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
ConsoleHelper.writeMessage(e.getMessage());
return;
}
}
if (clientConnected) {
ConsoleHelper.writeMessage("Соединение установлено. Для выхода наберите команду 'exit'.");
String input;
while (clientConnected) {
input = ConsoleHelper.readString();
if ("exit".equals(input)) {
break;
}
if (shouldSendTextFromConsole()) {
sendTextMessage(input);
}
}
} else {
ConsoleHelper.writeMessage("Произошла ошибка во время работы клиента.");
}
}
}
владимир
32 уровень
Ничерта не работает, как его запустить
Обсуждается
Комментарии (2)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
Artem Okunkov
21 февраля 2020, 19:43
Я обязательно доберусь до этого уровня и помогу тебе! Но это потребует времени.
0
владимир
22 февраля 2020, 06:42
я подожду, если не смогу решить проблему сам
0