Anonymous
Форматирование становится невозможным при использовании нескольких клиентов файла .jar.
Сообщение
Anonymous » 03 авг 2024, 03:40
Изображение ошибки
У меня возникла проблема: я пытаюсь создать приложение для обмена сообщениями. Все, что касается обмена сообщениями, работает нормально, но при открытии нескольких терминалов для общения между клиентами разрывы строк в конечном итоге будут разрываться, и строки появятся в конце других, тогда как их следует печатать внизу.Я использую maven для компиляции, может ли это быть проблемой?
Код: Выделить всё
import java.util.Scanner;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Emissor {
private static String target = "";
private static String currentUser = "";
private static String message;
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("ip"); // Alterar
factory.setUsername("user"); // Alterar
factory.setPassword("password"); // Alterar
factory.setVirtualHost("/");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
Scanner sc = new Scanner(System.in);
System.out.print("User: ");
currentUser = sc.nextLine();
channel.queueDeclare(currentUser, false, false, false, null);
safePrintln("\nLogado com sucesso!");
System.out.print("Destinatário: ");
target = sc.nextLine();
while (true) {
Consumer consumer = new DefaultConsumer(channel) {
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String messageReceived = new String(body, "UTF-8");
safePrintln("\n[x] Mensagem recebida: " + messageReceived);
safePrint(target + " >> ");
}
};
channel.basicConsume(currentUser, true, consumer);
safePrint(target + " >> ");
message = sc.nextLine();
if (message.isEmpty()) {
continue;
}
if (message.toLowerCase().equals("sair")) {
break;
}
channel.basicPublish("", target, null, message.getBytes("UTF-8"));
}
sc.close();
channel.close();
connection.close();
}
private static void safePrintln(String s) {
synchronized (System.out) {
System.out.println(s);
}
}
private static void safePrint(String s) {
synchronized (System.out) {
System.out.print(s);
}
}
}
Уже пытался синхронизировать потоки с помощью «synchronized (System.out)», но результаты те же.
Подробнее здесь:
https://stackoverflow.com/questions/788 ... f-jar-file
1722645650
Anonymous
Изображение ошибки У меня возникла проблема: я пытаюсь создать приложение для обмена сообщениями. Все, что касается обмена сообщениями, работает нормально, но при открытии нескольких терминалов для общения между клиентами разрывы строк в конечном итоге будут разрываться, и строки появятся в конце других, тогда как их следует печатать внизу.Я использую maven для компиляции, может ли это быть проблемой? [code]import java.util.Scanner; import com.rabbitmq.client.*; import java.io.IOException; public class Emissor { private static String target = ""; private static String currentUser = ""; private static String message; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("ip"); // Alterar factory.setUsername("user"); // Alterar factory.setPassword("password"); // Alterar factory.setVirtualHost("/"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); Scanner sc = new Scanner(System.in); System.out.print("User: "); currentUser = sc.nextLine(); channel.queueDeclare(currentUser, false, false, false, null); safePrintln("\nLogado com sucesso!"); System.out.print("Destinatário: "); target = sc.nextLine(); while (true) { Consumer consumer = new DefaultConsumer(channel) { public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String messageReceived = new String(body, "UTF-8"); safePrintln("\n[x] Mensagem recebida: " + messageReceived); safePrint(target + " >> "); } }; channel.basicConsume(currentUser, true, consumer); safePrint(target + " >> "); message = sc.nextLine(); if (message.isEmpty()) { continue; } if (message.toLowerCase().equals("sair")) { break; } channel.basicPublish("", target, null, message.getBytes("UTF-8")); } sc.close(); channel.close(); connection.close(); } private static void safePrintln(String s) { synchronized (System.out) { System.out.println(s); } } private static void safePrint(String s) { synchronized (System.out) { System.out.print(s); } } } [/code] Уже пытался синхронизировать потоки с помощью «synchronized (System.out)», но результаты те же. Подробнее здесь: [url]https://stackoverflow.com/questions/78827603/formatting-getting-all-messed-up-when-using-multiple-clients-of-jar-file[/url]