feature/separacao-gerenciadores #1

Merged
gustavo merged 31 commits from feature/separacao-gerenciadores into main 2026-09-30 18:34:54 -03:00
32 changed files with 526 additions and 279 deletions
Showing only changes of commit a86f4dbf82 - Show all commits

No files matched your search

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1 +1 @@
plugin.SocketTest plugin.TestChat
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../pitiupi/dist/pitiupi.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>
+84
View File
@@ -0,0 +1,84 @@
package GUI;
import plugin.TestChat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
public class ChatMenu extends JMenu {
private final TestChat testChat;
public ChatMenu(TestChat testChat) {
this.testChat = testChat;
this.setText("MP-Chat");
JMenuItem startPrivateChat = new JMenuItem("start Private Chat");
startPrivateChat.addActionListener(_ -> showPrivateChatDialog());
this.add(startPrivateChat);
}
public void newMenuItem(JMenuItem newMenuItem, ChatWindow chatWindow) {
newMenuItem.addActionListener(_ -> chatWindow.setVisible(true));
this.add(newMenuItem);
}
public void removeMenuItem(JMenuItem removeMenuItem) {
this.remove(removeMenuItem);
}
private void showPrivateChatDialog() {
JDialog dialog = new JDialog(
SwingUtilities.getWindowAncestor(this),
"Novo chat privado",
Dialog.ModalityType.APPLICATION_MODAL
);
JTextField ipField = new JTextField();
JButton startButton = new JButton("Iniciar");
JButton cancelButton = new JButton("Cancelar");
JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
contentPanel.setBorder(
BorderFactory.createEmptyBorder(10, 10, 10, 10)
);
JPanel ipPanel = new JPanel(new BorderLayout(5, 5));
ipPanel.add(new JLabel("IP:"), BorderLayout.WEST);
ipPanel.add(ipField, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel(
new FlowLayout(FlowLayout.RIGHT)
);
buttonsPanel.add(cancelButton);
buttonsPanel.add(startButton);
JLabel errorLabel = new JLabel("Não foi possível estabelecer a conexão.");
errorLabel.setForeground(Color.RED);
errorLabel.setVisible(false);
contentPanel.add(errorLabel, BorderLayout.NORTH);
contentPanel.add(ipPanel, BorderLayout.CENTER);
contentPanel.add(buttonsPanel, BorderLayout.SOUTH);
cancelButton.addActionListener(e -> dialog.dispose());
startButton.addActionListener(e -> {
String ip = ipField.getText();
if (testChat.openConnection(ip)) dialog.dispose();
else errorLabel.setVisible(true);
});
dialog.setContentPane(contentPanel);
dialog.pack();
dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this));
dialog.setVisible(true);
}
}
@@ -0,0 +1,94 @@
package GUI;
import net.TestChatMessage;
import pitiupi.GUI.MainWindow;
import javax.swing.*;
import java.awt.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public abstract class ChatWindow extends JFrame {
protected final MainWindow mainWindow;
private JTextArea receivedMessagesArea;
protected JTextField messageField;
public ChatWindow(MainWindow mainWindow) {
this.mainWindow = mainWindow;
initComponents();
}
private void initComponents() {
setTitle("Socket Test");
setSize(700, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
initReceivedMessagesPanel(mainPanel);
initBottomPanel(mainPanel);
setContentPane(mainPanel);
}
private void initReceivedMessagesPanel(JPanel mainPanel) {
receivedMessagesArea = new JTextArea();
receivedMessagesArea.setEditable(false);
receivedMessagesArea.setLineWrap(true);
receivedMessagesArea.setWrapStyleWord(true);
JScrollPane messagesScrollPane = new JScrollPane(receivedMessagesArea);
messagesScrollPane.setBorder(BorderFactory.createTitledBorder("Mensagens recebidas"));
mainPanel.add(messagesScrollPane, BorderLayout.CENTER);
}
private void initBottomPanel(JPanel mainPanel) {
messageField = new JTextField();
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
bottomPanel.add(messageField, BorderLayout.CENTER);
initButtons(bottomPanel);
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
}
protected abstract void initButtons(JPanel bottomPanel);
protected TestChatMessage createMessage(String tipoMensagem) {
try {
String nome = mainWindow.getUserName();
String ip = InetAddress.getLocalHost().getHostAddress();
String message = messageField.getText();
return new TestChatMessage(nome, ip, tipoMensagem, message);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public void receiveMessage(TestChatMessage msg) {
SwingUtilities.invokeLater(() -> {
String mensagem = String.format(
"[%s] %s (%s): %s%n",
msg.getTipoMensagem(),
msg.getNome(),
msg.getIp(),
msg.getMessage()
);
receivedMessagesArea.append(mensagem);
receivedMessagesArea.setCaretPosition(receivedMessagesArea.getDocument().getLength());
});
}
}
@@ -0,0 +1,46 @@
package GUI;
import net.TestChatMessage;
import pitiupi.GUI.MainWindow;
import pitiupi.net.tcp.TcpConnection;
import javax.swing.*;
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PrivateChatWindow extends ChatWindow {
private final TcpConnection connection;
public PrivateChatWindow(MainWindow mainWindow, TcpConnection connection) {
this.connection = connection;
super(mainWindow);
}
@Override
protected void initButtons(JPanel bottomPanel) {
JButton tcpButton = new JButton("TCP");
tcpButton.addActionListener(e -> sendTCP());
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
buttonsPanel.add(tcpButton);
bottomPanel.add(buttonsPanel, BorderLayout.EAST);
}
private void sendTCP() {
try {
TestChatMessage msg = createMessage("TCP Private");
connection.send(msg.toByteArray());
} catch (Exception ex) {
Logger.getLogger(
PrivateChatWindow.class.getName()
).log(Level.SEVERE, null, ex);
}
}
}
@@ -0,0 +1,93 @@
package GUI;
import net.TestChatMessage;
import pitiupi.GUI.MainWindow;
import javax.swing.*;
import java.awt.*;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PublicChatWindow extends ChatWindow {
private JTextField ipField;
public PublicChatWindow(MainWindow mainWindow) {
super(mainWindow);
}
@Override
protected void initButtons(JPanel bottomPanel) {
initIpField(bottomPanel);
initCommunicationButtons(bottomPanel);
}
private void initIpField(JPanel bottomPanel) {
ipField = new JTextField();
ipField.setPreferredSize(new Dimension(130, 30));
JPanel ipPanel = new JPanel(new BorderLayout(5, 5));
ipPanel.add(new JLabel("IP destino:"), BorderLayout.WEST);
ipPanel.add(ipField, BorderLayout.CENTER);
bottomPanel.add(ipPanel, BorderLayout.WEST);
}
private void initCommunicationButtons(JPanel bottomPanel) {
JButton tcpButton = new JButton("TCP");
JButton udpButton = new JButton("UDP");
JButton multicastButton = new JButton("Multicast");
tcpButton.addActionListener(e -> sendTCP());
udpButton.addActionListener(e -> sendUDP());
multicastButton.addActionListener(e -> sendMulticast());
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
buttonsPanel.add(tcpButton);
buttonsPanel.add(udpButton);
buttonsPanel.add(multicastButton);
bottomPanel.add(buttonsPanel, BorderLayout.EAST);
}
private void sendTCP() {
try {
TestChatMessage msg = createMessage("TCP Unicast");
InetAddress ip = InetAddress.getByName(ipField.getText());
mainWindow.getSocketTCP().send(msg, ip);
} catch (Exception ex) {
Logger.getLogger(PublicChatWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void sendUDP() {
try {
TestChatMessage msg = createMessage("UDP Unicast");
InetAddress ip = InetAddress.getByName(ipField.getText());
mainWindow.getSocketUDP().sendUnicast(msg, ip);
} catch (Exception ex) {
Logger.getLogger(PublicChatWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void sendMulticast() {
try {
TestChatMessage msg = createMessage("UDP Multicast");
mainWindow.getSocketUDP().sendMulticast(msg);
} catch (Exception ex) {
Logger.getLogger(PublicChatWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@@ -1,21 +0,0 @@
package GUI;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SocketTestMenu extends JMenu {
private final SocketTestWindow socketTestWindow;
public SocketTestMenu(SocketTestWindow socketTestWindow) {
this.socketTestWindow = socketTestWindow;
this.setText("Chat");
JMenuItem menuItem = new JMenuItem();
menuItem.setText("Show Chat Window");
menuItem.addActionListener(this::showTestWindow);
this.add(menuItem);
}
private void showTestWindow(ActionEvent ae) {
this.socketTestWindow.setVisible(true);
}
}
@@ -1,151 +0,0 @@
package GUI;
import net.TestMessage;
import pitiupi.GUI.MainWindow;
import javax.swing.*;
import java.awt.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SocketTestWindow extends JFrame {
private MainWindow mainWindow;
private JTextArea receivedMessagesArea;
private JTextField ipField;
private JTextField messageField;
private JButton tcpButton;
private JButton udpButton;
private JButton multicastButton;
public SocketTestWindow(MainWindow mainWindow) {
this.mainWindow = mainWindow;
initComponents();
}
public void initComponents() {
setTitle("Socket Test");
setSize(700, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
initReceivedMessagesPanel(mainPanel);
initBottomPanel(mainPanel);
setContentPane(mainPanel);
}
private void initReceivedMessagesPanel(JPanel mainPanel) {
receivedMessagesArea = new JTextArea();
receivedMessagesArea.setEditable(false);
receivedMessagesArea.setLineWrap(true);
receivedMessagesArea.setWrapStyleWord(true);
JScrollPane messagesScrollPane = new JScrollPane(receivedMessagesArea);
messagesScrollPane.setBorder(BorderFactory.createTitledBorder("Mensagens recebidas"));
mainPanel.add(messagesScrollPane, BorderLayout.CENTER);
}
private void initBottomPanel(JPanel mainPanel) {
ipField = new JTextField();
ipField.setPreferredSize(new Dimension(130, 30));
JPanel ipPanel = new JPanel(new BorderLayout(5, 5));
ipPanel.add(new JLabel("IP destino:"), BorderLayout.WEST);
ipPanel.add(ipField, BorderLayout.CENTER);
messageField = new JTextField();
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
bottomPanel.add(ipPanel, BorderLayout.WEST);
bottomPanel.add(messageField, BorderLayout.CENTER);
initButtons(bottomPanel);
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
}
private void initButtons(JPanel bottomPanel) {
tcpButton = new JButton("TCP");
udpButton = new JButton("UDP");
multicastButton = new JButton("Multicast");
tcpButton.addActionListener(e -> sendTCP());
udpButton.addActionListener(e -> sendUDP());
multicastButton.addActionListener(e -> sendMulticast());
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
buttonsPanel.add(tcpButton);
buttonsPanel.add(udpButton);
buttonsPanel.add(multicastButton);
bottomPanel.add(buttonsPanel, BorderLayout.EAST);
}
public void sendTCP() {
try {
TestMessage msg = createMessage("TCP Unicast");
InetAddress ip = InetAddress.getByName(ipField.getText());
mainWindow.getSocketTCP().send(msg.toByteArray(), ip);
} catch (Exception ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendUDP() {
try {
TestMessage msg = createMessage("UDP Unicast");
InetAddress ip = InetAddress.getByName(ipField.getText());
mainWindow.getSocketUDP().sendUnicast(msg.toByteArray(), ip);
} catch (Exception ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendMulticast() {
try {
TestMessage msg = createMessage("UDP Multicast");
mainWindow.getSocketUDP().sendMulticast(msg.toByteArray());
} catch (Exception ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
private TestMessage createMessage(String tipoMensagem) {
try {
String nome = mainWindow.getUserName();
String ip = InetAddress.getLocalHost().getHostAddress();
String message = messageField.getText();
return new TestMessage(nome, ip, tipoMensagem, message);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public void receiveMessage(TestMessage msg) {
SwingUtilities.invokeLater(() -> {
String mensagem = String.format(
"[%s] %s (%s): %s%n",
msg.getTipoMensagem(),
msg.getNome(),
msg.getIp(),
msg.getMessage()
);
receivedMessagesArea.append(mensagem);
receivedMessagesArea.setCaretPosition(
receivedMessagesArea.getDocument().getLength()
);
});
}
}
@@ -1 +1 @@
plugin.SocketTest plugin.TestChat
@@ -0,0 +1,61 @@
package control;
import GUI.ChatMenu;
import GUI.ChatWindow;
import GUI.PrivateChatWindow;
import GUI.PublicChatWindow;
import net.TestChatMessage;
import pitiupi.GUI.MainWindow;
import pitiupi.net.tcp.TcpConnection;
import javax.swing.*;
import java.util.HashMap;
public class ChatController {
MainWindow mainWindow;
ChatMenu chatMenu;
PublicChatWindow publicChatWindow;
private final HashMap<TcpConnection, JMenuItem> chatMenus;
private final HashMap<TcpConnection, ChatWindow> chatWindows;
public ChatController(MainWindow mainWindow, ChatMenu chatMenu) {
this.mainWindow = mainWindow;
publicChatWindow = new PublicChatWindow(mainWindow);
chatMenus = new HashMap<>();
chatWindows = new HashMap<>();
this.chatMenu = chatMenu;
this.chatMenu.newMenuItem(new JMenuItem("Show global chat"), publicChatWindow);
}
public void addChatWindow(TcpConnection tcpConnection) {
if (chatWindows.containsKey(tcpConnection)) return;
PrivateChatWindow newChat = new PrivateChatWindow(mainWindow, tcpConnection);
chatWindows.put(tcpConnection, newChat);
JMenuItem newMenuItem = new JMenuItem();
chatMenus.put(tcpConnection, newMenuItem);
newMenuItem.setText(tcpConnection.getAddress().toString());
chatMenu.newMenuItem(newMenuItem, newChat);
}
public void removeChatWindow(TcpConnection tcpConnection) {
ChatWindow removedWindow = chatWindows.remove(tcpConnection);
JMenuItem removedMenu = chatMenus.remove(tcpConnection);
chatMenu.removeMenuItem(removedMenu);
removedWindow.setVisible(false);
removedWindow.dispose();
}
public void receivePublic(TestChatMessage message) {
publicChatWindow.receiveMessage(message);
}
public void receivePrivate(TcpConnection tcpConnection, TestChatMessage message) {
chatWindows.get(tcpConnection).receiveMessage(message);
}
}
@@ -2,20 +2,20 @@ package net;
import pitiupi.net.Message; import pitiupi.net.Message;
public class TestMessage extends Message { public class TestChatMessage extends Message {
private String nome; private String nome;
private String ip; private String ip;
private String tipoMensagem; private String tipoMensagem;
private String message; private String message;
public TestMessage(String nome, String ip, String tipoMensagem, String message) { public TestChatMessage(String nome, String ip, String tipoMensagem, String message) {
this.nome = nome; this.nome = nome;
this.ip = ip; this.ip = ip;
this.tipoMensagem = tipoMensagem; this.tipoMensagem = tipoMensagem;
this.message = message; this.message = message;
} }
public TestMessage(){} public TestChatMessage(){}
public String getNome() { public String getNome() {
return nome; return nome;
@@ -1,56 +0,0 @@
package plugin;
import GUI.SocketTestMenu;
import GUI.SocketTestWindow;
import net.TestMessage;
import pitiupi.GUI.MainWindow;
import pitiupi.net.Message;
import pitiupi.plugin.Plugin;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class SocketTest implements Plugin{
SocketTestWindow socketTestWindow;
@Override
public String getName() {
return "Test Socket";
}
@Override
public String getAuthor() {
return "Gustavo Henrique";
}
@Override
public String getVersion() {
return "0";
}
@Override
public void createPlugin(MainWindow mainWindow) {
this.socketTestWindow = new SocketTestWindow(mainWindow);
mainWindow.addMenu(new SocketTestMenu(socketTestWindow));
}
@Override
public Message getMessage() {
return new TestMessage();
}
@Override
public void receiveMessage(byte[] bytes) {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois;
try {
ois = new ObjectInputStream(bis);
if (ois.readObject() instanceof TestMessage msg) {
this.socketTestWindow.receiveMessage(msg);
}
} catch (IOException | ClassNotFoundException ex) {
System.out.println(ex.toString());
}
}
}
+104
View File
@@ -0,0 +1,104 @@
package plugin;
import GUI.ChatMenu;
import control.ChatController;
import net.TestChatMessage;
import pitiupi.GUI.MainWindow;
import pitiupi.net.Message;
import pitiupi.net.tcp.TcpConnection;
import pitiupi.plugin.PrivateConnectionPlugin;
import javax.swing.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetAddress;
public class TestChat implements PrivateConnectionPlugin{
ChatController chatController;
MainWindow mainWindow;
@Override
public String getName() {
return "MultiProtocol chat";
}
@Override
public String getAuthor() {
return "Gustavo Henrique";
}
@Override
public String getVersion() {
return "0";
}
@Override
public String getIdentifier() {
return "Multi.Protocol.Chat.Pitiupi";
}
@Override
public void createPlugin(MainWindow mainWindow) {
this.mainWindow = mainWindow;
ChatMenu chatMenu = new ChatMenu(this);
chatController = new ChatController(mainWindow, chatMenu);
mainWindow.addMenu(chatMenu);
}
@Override
public Message getMessage() {
return new TestChatMessage();
}
@Override
public void receiveMessage(byte[] message) {
TestChatMessage testChatMessage = parseMessage(message);
chatController.receivePublic(testChatMessage);
}
@Override
public void receivePrivateConnection(TcpConnection tcpConnection) {
SwingUtilities.invokeLater(() -> {
chatController.addChatWindow(tcpConnection);
});
}
@Override
public void receiveBytes(TcpConnection connection, byte[] bytes) {
TestChatMessage testChatMessage = parseMessage(bytes);
chatController.receivePrivate(connection, testChatMessage);
}
@Override
public void onSocketClosed(TcpConnection tcpConnection) {
chatController.removeChatWindow(tcpConnection);
}
public boolean openConnection(String ip) {
try {
mainWindow.getSocketTCP().createPrivateConnection(InetAddress.getByName(ip), getIdentifier(), getIdentifier());
return true;
}
catch (Exception e) {
System.out.println("Error opening connection: " + e.getMessage());
}
return false;
}
private TestChatMessage parseMessage(byte[] bytes) {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois;
try {
ois = new ObjectInputStream(bis);
if (ois.readObject() instanceof TestChatMessage msg) {
return msg;
}
} catch (IOException | ClassNotFoundException ex) {
System.out.println(ex.toString());
}
return null;
}
}
Binary file not shown.
Binary file not shown.
-1
View File
@@ -48,7 +48,6 @@ public final class Login extends JDialog {
public void initComponents() { public void initComponents() {
this.setTitle("Login"); this.setTitle("Login");
String nomeSalvo = prefs.get(PREF_NOME, System.getProperty("user.name")); String nomeSalvo = prefs.get(PREF_NOME, System.getProperty("user.name"));
int portaSalva = prefs.getInt(PREF_PORTA, 8000); int portaSalva = prefs.getInt(PREF_PORTA, 8000);
@@ -102,6 +102,9 @@ public class ConnectionFactory {
if (handshake == null) return null; if (handshake == null) return null;
connection.send(handshake.createResponse().toByteArray());
connection.setSender(handshake.getSender()); connection.setSender(handshake.getSender());
connection.setReceiver(handshake.getReceiver()); connection.setReceiver(handshake.getReceiver());
connection.setPrivate(handshake.isPrivate()); connection.setPrivate(handshake.isPrivate());
@@ -148,10 +151,9 @@ public class ConnectionFactory {
Object object = ois.readObject(); Object object = ois.readObject();
if (object instanceof Message message) { if (object instanceof Message message) {
if (SysInfoMessage.parseSystemInfo(message) != null) { SysInfoMessage sysInfo = SysInfoMessage.parseSystemInfo(bytes);
//TODO: Tratar erros if (sysInfo != null) return null;
return null;
}
if (message instanceof HandshakeMessage handshake) { if (message instanceof HandshakeMessage handshake) {
return (validateHandshake(handshake, connection)) ? handshake : null; return (validateHandshake(handshake, connection)) ? handshake : null;
@@ -218,6 +220,7 @@ public class ConnectionFactory {
); );
return false; return false;
} }
return true; return true;
} }
} }
+6 -12
View File
@@ -36,7 +36,7 @@ public class SocketTCP extends Thread {
private final ExecutorService connectionExecutor = Executors.newCachedThreadPool(); private final ExecutorService connectionExecutor = Executors.newCachedThreadPool();
private final TcpConnectionManager tcpConnectionManager; private final ConnectionManager connectionManager;
private ServerSocket serverSocket; private ServerSocket serverSocket;
private InetAddress address; private InetAddress address;
@@ -95,7 +95,6 @@ public class SocketTCP extends Thread {
System.out.println("Could not establish TCP connection."); System.out.println("Could not establish TCP connection.");
return false; return false;
} }
connection.send(msg.toByteArray()); connection.send(msg.toByteArray());
} catch (Exception ex) { } catch (Exception ex) {
System.out.println("Could not send TCP message."); System.out.println("Could not send TCP message.");
@@ -207,7 +206,7 @@ public class SocketTCP extends Thread {
saveConnection(connection); saveConnection(connection);
connectionExecutor.submit(() -> { connectionExecutor.submit(() -> {
startReceiver(connection, false); startReceiver(connection);
}); });
return connection; return connection;
@@ -228,7 +227,7 @@ public class SocketTCP extends Thread {
if (connection == null) return; if (connection == null) return;
saveConnection(connection); saveConnection(connection);
startReceiver(connection, true); startReceiver(connection);
}); });
} }
@@ -259,10 +258,9 @@ public class SocketTCP extends Thread {
* estabelecimento da conexão.</p> * estabelecimento da conexão.</p>
* *
* @param connection conexão cujo fluxo de entrada será processado. * @param connection conexão cujo fluxo de entrada será processado.
* @param notify indica se o plugin destinatário deve ser notificado sobre
* o recebimento de uma nova conexão privada.
*/ */
private void startReceiver(TcpConnection connection, boolean notify) { private void startReceiver(TcpConnection connection) {
if (!connection.isPrivate()) { if (!connection.isPrivate()) {
publicConnectionReceiver(connection); publicConnectionReceiver(connection);
return; return;
@@ -302,12 +300,8 @@ public class SocketTCP extends Thread {
while (running) { while (running) {
try { try {
byte[] bytes = connection.receive(); byte[] bytes = connection.receive();
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis)) {
Object object = ois.readObject(); SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(bytes);
if (object instanceof Message message) {
SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(message);
if (sysMessage == null) { if (sysMessage == null) {
pluginManager.handlePublicMessage(message); pluginManager.handlePublicMessage(message);
@@ -48,11 +48,4 @@ public class SysInfoMessage extends Message {
} }
return null; return null;
} }
public static SysInfoMessage parseSystemInfo(Message message) {
if (message instanceof SysInfoMessage) {
return (SysInfoMessage) message;
}
return null;
}
} }
+4 -20
View File
@@ -152,19 +152,17 @@ public class SocketUDP extends Thread {
} }
throw ex; throw ex;
} }
HeartbeatMessage heartbeat = tryParseHeartbeat(msgPacket.getData()); HeartbeatMessage heartbeat = tryParseHeartbeat(msgPacket.getData());
if (heartbeat != null) { if (heartbeat != null) {
connectionManager.receiveHeartbeat(heartbeat, msgPacket.getAddress()); connectionManager.receiveHeartbeat(heartbeat, msgPacket.getAddress());
continue; continue;
} }
Message message = tryParseMessage(msgPacket.getData()); for (Plugin plugin : main.getPlugins()) {
if (message == null) {
continue;
}
System.out.println(msgPacket.getAddress().toString()); System.out.println(msgPacket.getAddress().toString());
pluginManager.handlePublicMessage(message); pluginManager.handlePublicMessage(msgPacket.getData());
}
} }
} }
@@ -186,20 +184,6 @@ public class SocketUDP extends Thread {
} }
} }
private Message tryParseMessage(byte[] data) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bis);
Object object = ois.readObject();
if (object instanceof Message message) return message;
return null;
} catch (IOException | ClassNotFoundException ex) {
return null;
}
}
/** /**
* Inicia a recepção de mensagens UDP. * Inicia a recepção de mensagens UDP.
*/ */
+1 -1
View File
@@ -47,6 +47,6 @@ public interface Plugin {
* *
* @param message mensagem serializada recebida. * @param message mensagem serializada recebida.
*/ */
public void receiveMessage(Message message); public void receiveMessage(byte[] message);
} }
@@ -4,6 +4,6 @@ import pitiupi.net.tcp.TcpConnection;
public interface PrivateConnectionPlugin extends Plugin { public interface PrivateConnectionPlugin extends Plugin {
public void receivePrivateConnection(TcpConnection connection); public void receivePrivateConnection(TcpConnection connection);
public void receiveBytes(byte[] bytes); public void receiveBytes(TcpConnection connection, byte[] bytes);
public void onSocketClosed(TcpConnection connection); public void onSocketClosed(TcpConnection connection);
} }