Author SHA1 Message Date
GustavoHMDS 23559dcc06 WIP bug fix 3 2026-09-29 01:20:48 -03:00
GustavoHMDS fa4ee046b1 WIP BugFix 3 2026-09-29 01:13:42 -03:00
GustavoHMDS 0c71a85cba WIP bug fix 3 2026-09-29 00:21:04 -03:00
GustavoHMDS e7c8983775 WIP TCP bug fix 2 2026-09-28 22:05:14 -03:00
GustavoHMDS 0ec3129a22 WIP TCP bug fix 2026-09-28 21:43:17 -03:00
GustavoHMDS ba2f41daf7 WIP bug fix 2026-09-28 18:59:20 -03:00
GustavoHMDS 57059c3ef0 WIP bugfix 2026-09-28 12:42:49 -03:00
39 changed files with 774 additions and 641 deletions

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;
public class TestMessage extends Message {
public class TestChatMessage extends Message {
private String nome;
private String ip;
private String tipoMensagem;
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.ip = ip;
this.tipoMensagem = tipoMensagem;
this.message = message;
}
public TestMessage(){}
public TestChatMessage(){}
public String getNome() {
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() {
this.setTitle("Login");
String nomeSalvo = prefs.get(PREF_NOME, System.getProperty("user.name"));
int portaSalva = prefs.getInt(PREF_PORTA, 8000);
+95 -30
View File
@@ -5,11 +5,13 @@
*/
package pitiupi.GUI;
import pitiupi.control.ConnectionManager;
import pitiupi.control.PluginManager;
import pitiupi.net.tcp.SocketTCP;
import pitiupi.net.udp.SocketUDP;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JMenu;
import pitiupi.control.PluginLoader;
import pitiupi.plugin.Plugin;
import pitiupi.control.HeartbeatManager;
/**
@@ -34,12 +36,20 @@ public class MainWindow extends javax.swing.JFrame {
private javax.swing.JPanel statusPanel;
private javax.swing.JTabbedPane tabbedPane;
private HeartbeatManager heartbeatManager;
private OnlineUsersPanel onlineUsersPanel;
private String userName;
private ConnectionManager connectionManager;
private PluginManager pluginManager;
private SocketUDP socketUDP;
private SocketTCP socketTCP;
private String userName;
private int port;
private String pitiupiIdentifier;
private PluginLoader pluginManager;
private final List<Plugin> plugins;
/**
* Cria a janela principal da aplicação.
@@ -49,18 +59,22 @@ public class MainWindow extends javax.swing.JFrame {
*/
public MainWindow(String userName, int port) {
this.userName = userName;
pluginManager = new PluginManager(this);
loadPlugins();
connectionManager = new ConnectionManager(this, pluginManager, port);
menuBar = new MenuBar(this);
initComponents();
this.port = port;
this.pitiupiIdentifier = "Pitiupi.Alice.2026";
this.menuBar = new MenuBar(this);
this.plugins = new ArrayList<>();
this.initComponents();
}
private void initComponents() {
initGUI();
initSocket();
initHeartbeat();
initPlugins();
this.setSize(new java.awt.Dimension(1024, 768));
}
private void initGUI() {
this.setJMenuBar(menuBar);
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setTitle("Share My Sheet");
@@ -72,19 +86,34 @@ public class MainWindow extends javax.swing.JFrame {
jScrollPane1.setViewportView(tabbedPane);
statusPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
updateStatus();
status.setText("Connected on port " + this.port + " name " + this.userName);
statusPanel.add(status);
this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
this.getContentPane().add(statusPanel, java.awt.BorderLayout.PAGE_END);
this.onlineUsersPanel = new OnlineUsersPanel();
this.connectionManager.addPeerListener(onlineUsersPanel);
this.getContentPane().add(this.onlineUsersPanel, java.awt.BorderLayout.LINE_END);
this.pack();
}
this.setSize(new java.awt.Dimension(1024, 768));
private void initSocket() {
this.socketUDP = new SocketUDP(this);
this.socketTCP = new SocketTCP(this);
this.socketUDP.start();
this.socketTCP.start();
}
private void initHeartbeat() {
this.heartbeatManager = new HeartbeatManager(this);
this.onlineUsersPanel = new OnlineUsersPanel();
this.heartbeatManager.addPeerListener(this.onlineUsersPanel);
this.getContentPane().add(this.onlineUsersPanel, java.awt.BorderLayout.LINE_END);
this.heartbeatManager.start();
}
private void initPlugins() {
this.pluginManager = new PluginLoader(this);
this.pluginManager.loadPlugins();
}
public void exit() {
@@ -93,29 +122,65 @@ public class MainWindow extends javax.swing.JFrame {
System.exit(0);
}
public HeartbeatManager getHeartbeatManager() {
return heartbeatManager;
}
public String getUserName(){
return this.userName;
}
public ConnectionManager getConnectionManager() {
return connectionManager;
}
public void loadPlugins() {
pluginManager.loadPlugins();
public String getIdentifier(){
return this.pitiupiIdentifier;
}
public void addMenu(JMenu menu) {
this.menuBar.addPlugin(menu);
}
public int getPort() {
return this.port;
}
public SocketUDP getSocketUDP() {
return this.socketUDP;
}
public SocketTCP getSocketTCP() {
return this.socketTCP;
}
public List<Plugin> getPlugins() {
return plugins;
}
public void setUserName(String userName) {
this.userName = userName;
updateStatus();
}
private void updateStatus() {
this.status.setText("Connected on port " + connectionManager + " name " + this.userName);
public void setPort(int port) {
this.port = port;
reconnect();
updateStatus();
}
private void updateStatus() {
this.status.setText("Connected on port " + this.port + " name " + this.userName);
}
private void reconnect() {
if (this.socketUDP != null) {
this.socketUDP.close();
}
if (this.socketTCP != null) {
this.socketTCP.close();
}
this.socketUDP = new SocketUDP(this);
this.socketTCP = new SocketTCP(this);
this.socketUDP.start();
this.socketTCP.start();
}
}
+1 -1
View File
@@ -80,7 +80,7 @@ public class MenuBar extends JMenuBar {
login.setVisible(true);
mainWindow.setUserName(login.getName());
mainWindow.getConnectionManager().setPort(login.getPort());
mainWindow.setPort(login.getPort());
login.dispose();
}
@@ -1,104 +0,0 @@
package pitiupi.control;
import pitiupi.GUI.MainWindow;
import pitiupi.net.HeartbeatMessage;
import pitiupi.net.Message;
import pitiupi.net.tcp.SocketTCP;
import pitiupi.net.tcp.TcpConnection;
import pitiupi.net.udp.SocketUDP;
import java.net.InetAddress;
public class ConnectionManager {
private final String pitiupiIdentifier;
private PluginManager pluginManager;
private HeartbeatManager heartbeatManager;
private SocketTCP socketTCP;
private SocketUDP socketUDP;
private int port;
public ConnectionManager(MainWindow main, PluginManager pluginManager, int port) {
this.pluginManager = pluginManager;
this.port = port;
pitiupiIdentifier = "Pitiupi.Alice.2026";
reconnect();
heartbeatManager = new HeartbeatManager(main, this);
heartbeatManager.start();
}
public TcpConnection connectPluginTcp(InetAddress destinationAdress, String senderId, String receiverId) {
return socketTCP.createPrivateConnection(destinationAdress, senderId, receiverId);
}
public boolean sendTcp(Message message, InetAddress destinationAddress) {
return socketTCP.send(message, destinationAddress);
}
public boolean sendUdpUnicast(Message message, InetAddress destinationAddress) {
try {
socketUDP.sendUnicast(message, destinationAddress);
return true;
} catch (Exception ex) {
return false;
}
}
public boolean sendUdpMulticast(Message message) {
try {
socketUDP.sendMulticast(message);
return true;
} catch (Exception ex) {
return false;
}
}
public void broadcastLocal(Message message) {
pluginManager.handlePublicMessage(message);
}
public boolean sendLocal(byte[] message, String receiverId) {
return pluginManager.handlePrivateMessage(message, receiverId);
}
public void addPeerListener(PeerListener peerListener) {
heartbeatManager.addPeerListener(peerListener);
}
public void receiveHeartbeat(HeartbeatMessage message, InetAddress destinationAddress) {
heartbeatManager.receiveHeartbeat(message, destinationAddress);
}
public void setPort(int port) {
this.port = port;
reconnect();
}
public int getPort() {
return port;
}
public String getIdentifier(){
return this.pitiupiIdentifier;
}
private void reconnect() {
if (this.socketUDP != null) {
this.socketUDP.close();
}
if (this.socketTCP != null) {
this.socketTCP.close();
}
this.socketUDP = new SocketUDP(this, pluginManager);
this.socketTCP = new SocketTCP(this, pluginManager);
this.socketUDP.start();
this.socketTCP.start();
}
}
@@ -30,7 +30,6 @@ public class HeartbeatManager {
private static final long PEER_TIMEOUT_MS = 15000; // ~3 batimentos perdidos
private final MainWindow mainWindow;
private final ConnectionManager connectionManager;
private final Map<String, PeerInfo> peers = new ConcurrentHashMap<>();
private final List<PeerListener> listeners = new CopyOnWriteArrayList<>();
private ScheduledExecutorService scheduler;
@@ -42,9 +41,8 @@ public class HeartbeatManager {
* @param mainWindow janela principal utilizada para obter o nome do usuário
* e o socket de comunicação.
*/
public HeartbeatManager(MainWindow mainWindow, ConnectionManager connectionManager) {
public HeartbeatManager(MainWindow mainWindow) {
this.mainWindow = mainWindow;
this.connectionManager = connectionManager;
}
/**
@@ -66,8 +64,12 @@ public class HeartbeatManager {
}
private void announce() {
HeartbeatMessage msg = new HeartbeatMessage(mainWindow.getUserName(), instanceId);
connectionManager.sendUdpMulticast(msg);
try {
HeartbeatMessage msg = new HeartbeatMessage(mainWindow.getUserName(), instanceId);
mainWindow.getSocketUDP().sendMulticast(msg);
} catch (IOException ex) {
Logger.getLogger(HeartbeatManager.class.getName()).log(Level.WARNING, "Falha ao enviar heartbeat", ex);
}
}
// Chamado pelo Socket quando um pacote é identificado como heartbeat
+27 -26
View File
@@ -4,12 +4,14 @@
*/
package pitiupi.control;
import java.awt.List;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.ArrayList;
import java.util.ServiceLoader;
import java.util.Vector;
import pitiupi.GUI.MainWindow;
import pitiupi.Main;
import pitiupi.plugin.Plugin;
@@ -31,7 +33,7 @@ public class PluginLoader {
this.mainWindow = main;
}
public void loadPlugins(List<Plugin> plugins, HashSet<String> loadedJars) {
public void loadPlugins() {
File pluginDir = new File("plugins");
File[] jarFiles = pluginDir.listFiles((dir, name) -> name.endsWith(".jar"));
@@ -40,34 +42,33 @@ public class PluginLoader {
return;
}
for (File file : jarFiles) {
if (loadedJars.contains(file.getName())) {
continue;
try {
// 2. Convert jar file paths into URLs
ArrayList urls = new ArrayList();
for (File file : jarFiles) {
urls.add(file.toURI().toURL());
System.out.println("Discovered plugin package: " + file.getName());
}
System.out.println("Discovered plugin package: " + file.getName());
// 3. Create a class loader isolated from the application's default loader
URLClassLoader pluginClassLoader = new URLClassLoader(
(URL[])urls.toArray(new URL[0]),
Main.class.getClassLoader()
);
System.out.println(pluginClassLoader);
try {
URLClassLoader classLoader = new URLClassLoader(
new URL[]{file.toURI().toURL()},
Main.class.getClassLoader()
);
// 4. Locate and instantiate all classes implementing the Plugin interface
ServiceLoader<Plugin> serviceLoader = ServiceLoader.load(Plugin.class, pluginClassLoader);
ServiceLoader<Plugin> serviceLoader = ServiceLoader.load(Plugin.class, classLoader);
for (Plugin plugin : serviceLoader) {
System.out.println("Loading: " + plugin.getName());
plugin.createPlugin(this.mainWindow);
plugins.add(plugin);
loadedJars.add(file.getName());
}
} catch (Exception e) {
System.out.println("Failed to load plugin " + file.getName());
e.printStackTrace();
System.out.println("\n--- Executing Discovered Plugins ---" + serviceLoader.findFirst());
for (Plugin plugin : serviceLoader) {
System.out.println("Loading: " + plugin.getName());
plugin.createPlugin(this.mainWindow);
this.mainWindow.getPlugins().add(plugin);
}
} catch (MalformedURLException e) {
System.out.println(e.toString());
}
}
}
@@ -1,71 +0,0 @@
package pitiupi.control;
import pitiupi.GUI.MainWindow;
import pitiupi.net.Message;
import pitiupi.net.tcp.TcpConnection;
import pitiupi.plugin.Plugin;
import pitiupi.plugin.PrivateConnectionPlugin;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class PluginManager {
private PluginLoader pluginLoader;
private final List<Plugin> plugins;
private final HashSet<String> loadedJars;
public PluginManager(MainWindow main) {
this.pluginLoader = new PluginLoader(main);
this.plugins = new ArrayList<>();
this.loadedJars = new HashSet<>();
}
public void loadPlugins() {
pluginLoader.loadPlugins(plugins, loadedJars);
}
public void handlePublicMessage(Message msg) {
for (Plugin plugin : plugins) {
plugin.receiveMessage(msg);
}
}
private Plugin getPlugin(String pluginId) {
for (Plugin plugin : plugins) {
if (plugin.getIdentifier().equals(pluginId)) return plugin;
}
return null;
}
public boolean handlePrivateMessage(byte[] msg, String receiverId) {
Plugin plugin = getPlugin(receiverId);
if (plugin == null) return false;
if (plugin instanceof PrivateConnectionPlugin privatePlugin) {
privatePlugin.receiveBytes(msg);
return true;
}
return false;
}
public boolean handleConnection(TcpConnection connection, String receiverId) {
Plugin plugin = getPlugin(receiverId);
if (plugin == null) return false;
if (plugin instanceof PrivateConnectionPlugin privatePlugin) {
privatePlugin.receivePrivateConnection(connection);
return true;
}
return false;
}
public void handleDisconnection(TcpConnection connection, String receiverId) {
Plugin plugin = getPlugin(receiverId);
if (plugin instanceof PrivateConnectionPlugin privatePlugin) {
privatePlugin.onSocketClosed(connection);
}
}
}
@@ -102,6 +102,9 @@ public class ConnectionFactory {
if (handshake == null) return null;
connection.send(handshake.createResponse().toByteArray());
connection.setSender(handshake.getSender());
connection.setReceiver(handshake.getReceiver());
connection.setPrivate(handshake.isPrivate());
@@ -148,10 +151,9 @@ public class ConnectionFactory {
Object object = ois.readObject();
if (object instanceof Message message) {
if (SysInfoMessage.parseSystemInfo(message) != null) {
//TODO: Tratar erros
return null;
}
SysInfoMessage sysInfo = SysInfoMessage.parseSystemInfo(bytes);
if (sysInfo != null) return null;
if (message instanceof HandshakeMessage handshake) {
return (validateHandshake(handshake, connection)) ? handshake : null;
@@ -218,6 +220,7 @@ public class ConnectionFactory {
);
return false;
}
return true;
}
}
@@ -27,7 +27,7 @@ import java.util.stream.Collectors;
* peers ativos para encerrar conexões associadas a peers que deixaram de
* estar disponíveis.</p>
*/
class TcpConnectionManager implements PeerListener {
class ConnectionManager implements PeerListener {
private final Logger logger;
private final Map<InetAddress, TcpConnection> publicConnections;
private final Map<InetAddress, List<TcpConnection>> privateConnections;
@@ -35,7 +35,7 @@ class TcpConnectionManager implements PeerListener {
/**
* Cria um gerenciador de conexões TCP vazio.
*/
public TcpConnectionManager() {
public ConnectionManager() {
publicConnections = new ConcurrentHashMap<>();
privateConnections = new ConcurrentHashMap<>();
+104 -109
View File
@@ -1,12 +1,11 @@
package pitiupi.net.tcp;
import pitiupi.GUI.MainWindow;
import pitiupi.control.ConnectionManager;
import pitiupi.control.PluginManager;
import pitiupi.net.Message;
import pitiupi.plugin.Plugin;
import pitiupi.plugin.PrivateConnectionPlugin;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.Objects;
@@ -36,13 +35,12 @@ public class SocketTCP extends Thread {
private final ExecutorService connectionExecutor = Executors.newCachedThreadPool();
private final TcpConnectionManager tcpConnectionManager;
private final ConnectionManager connectionManager;
private ServerSocket serverSocket;
private InetAddress address;
private final ConnectionManager connectionManager;
private final PluginManager pluginManager;
private final MainWindow main;
private volatile boolean running = true;
@@ -53,18 +51,15 @@ public class SocketTCP extends Thread {
* com os peers são estabelecidas sob demanda durante o envio ou aceitas
* quando iniciadas por outros peers.</p>
*
* @param connectionManager interface de conexão da aplicação, usada para obter a porta,
* o identificador local e os plugins disponíveis.
* @param main janela principal da aplicação, usada para obter a porta,
* o identificador local e os plugins disponíveis.
*/
public SocketTCP(ConnectionManager connectionManager, PluginManager pluginManager) {
this.connectionManager = connectionManager;
this.pluginManager = pluginManager;
public SocketTCP(MainWindow main) {
this.main = main;
logger = Logger.getLogger(getClass().getName());
tcpConnectionManager = new TcpConnectionManager();
connectionManager = new ConnectionManager();
try {
serverSocket = new ServerSocket(connectionManager.getPort());
serverSocket = new ServerSocket(main.getPort());
address = InetAddress.getByName(InetAddress.getLocalHost().getHostAddress());
} catch (IOException ex) {
System.out.println("There is no socket connection. Sorry.");
@@ -83,33 +78,25 @@ public class SocketTCP extends Thread {
* @param msg mensagem que será enviada.
* @param destinationAddress endereço IP do peer que receberá a mensagem.
*/
public boolean send(Message msg, InetAddress destinationAddress) {
public void send(Message msg, InetAddress destinationAddress) {
try {
TcpConnection connection = getPublicConnection(
destinationAddress,
connectionManager.getIdentifier(),
connectionManager.getIdentifier()
);
TcpConnection connection = getPublicConnection(destinationAddress, main.getIdentifier(), main.getIdentifier());
if (connection == null) {
System.out.println("Could not establish TCP connection.");
return false;
return;
}
connection.send(msg.toByteArray());
} catch (Exception ex) {
System.out.println("Could not send TCP message.");
System.out.println(ex.toString());
return false;
}
return true;
}
/**
* Estabelece uma conexão TCP privada com um plugin específico do peer de destino.
*
* <p>A conexão é criada como privada e passa a ser gerenciada pelo
* {@link TcpConnectionManager}. O método também inicia a tarefa responsável
* {@link ConnectionManager}. O método também inicia a tarefa responsável
* por receber os dados dessa conexão.</p>
*
* @param destinationAddress endereço IP do peer de destino.
@@ -128,11 +115,11 @@ public class SocketTCP extends Thread {
* Obtém uma conexão TCP pública existente com o peer de destino ou estabelece
* uma nova caso não exista uma conexão válida.
*
* <p>As conexões públicas são gerenciadas pelo {@link TcpConnectionManager}.
* <p>As conexões públicas são gerenciadas pelo {@link ConnectionManager}.
* O método primeiro verifica se já existe uma conexão pública registrada
* para o endereço de destino e, caso ela exista e não esteja fechada,
* reutiliza-a. Caso contrário, uma nova conexão pública é estabelecida,
* registrada no {@link TcpConnectionManager} e disponibilizada para uso.</p>
* registrada no {@link ConnectionManager} e disponibilizada para uso.</p>
*
* <p>O acesso ao método é sincronizado para evitar que múltiplas threads
* estabeleçam simultaneamente conexões públicas para o mesmo peer.</p>
@@ -146,7 +133,7 @@ public class SocketTCP extends Thread {
private synchronized TcpConnection getPublicConnection(InetAddress destinationAddress, String senderId, String receiverId) {
TcpConnection connection;
connection = tcpConnectionManager.getPublicConnection(destinationAddress);
connection = connectionManager.getPublicConnection(destinationAddress);
if (connection != null && !connection.isClosed()) return connection;
connection = establishOutgoingConnection(destinationAddress, senderId, receiverId, false);
@@ -159,7 +146,7 @@ public class SocketTCP extends Thread {
*
* <p>Cada socket aceito é encaminhado para processamento assíncrono,
* interpretado como uma {@link TcpConnection}, registrado pelo
* {@link TcpConnectionManager} e associado ao receptor adequado.</p>
* {@link ConnectionManager} e associado ao receptor adequado.</p>
*/
private void receive() {
while (running) {
@@ -201,13 +188,13 @@ public class SocketTCP extends Thread {
throw new IllegalArgumentException("Connections to the local host are forbidden.");
}
TcpConnection connection = ConnectionFactory.createConnection(destinationAddress, connectionManager.getPort(), sender, receiver, isPrivate);
TcpConnection connection = ConnectionFactory.createConnection(destinationAddress, main.getPort(), sender, receiver, isPrivate);
if (connection == null) return null;
saveConnection(connection);
connectionExecutor.submit(() -> {
startReceiver(connection, false);
startReceiver(connection);
});
return connection;
@@ -228,7 +215,7 @@ public class SocketTCP extends Thread {
if (connection == null) return;
saveConnection(connection);
startReceiver(connection, true);
startReceiver(connection);
});
}
@@ -242,10 +229,10 @@ public class SocketTCP extends Thread {
*/
private void saveConnection(TcpConnection connection) {
if (connection.isPrivate()) {
tcpConnectionManager.addPrivateConnection(connection);
connectionManager.addPrivateConnection(connection);
}
else {
tcpConnectionManager.addPublicConnection(connection);
connectionManager.addPublicConnection(connection);
}
}
@@ -259,30 +246,55 @@ public class SocketTCP extends Thread {
* estabelecimento da conexão.</p>
*
* @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()) {
publicConnectionReceiver(connection);
return;
}
if (connection.getReceiver().equals(connectionManager.getIdentifier())) {
if (connection.getReceiver().equals(main.getIdentifier())) {
systemConnectionReceiver(connection);
return;
}
if (pluginManager.handleConnection(connection, connection.getReceiver()))
privateConnectionReceiver(connection);
else {
Plugin receiver = findConnectionReceiver(connection);
if (receiver instanceof PrivateConnectionPlugin plugin) {
plugin.receivePrivateConnection(connection);
privateConnectionReceiver(connection, plugin);
}
}
/**
* Localiza o plugin responsável por receber uma conexão privada.
*
* <p>A busca é feita pelo identificador do destinatário informado na
* própria conexão. Caso nenhum plugin correspondente seja encontrado,
* uma mensagem de erro é enviada ao peer remoto.</p>
*
* @param connection conexão privada cujo destinatário será localizado.
* @return o plugin com o identificador correspondente ao destinatário,
* ou {@code null} se nenhum plugin for encontrado.
*/
private Plugin findConnectionReceiver(TcpConnection connection) {
Plugin receiver = null;
for(Plugin plugin : main.getPlugins()) {
if (plugin.getIdentifier().equals(connection.getReceiver())) {
receiver = plugin;
break;
}
}
if (receiver == null) {
SysInfoMessage.sendSystemInfo(
connection,
SysInfoType.RECEIVER_NOT_FOUND,
"This peer does not have the plugin: " + connection.getReceiver()
);
}
return receiver;
}
/**
@@ -294,7 +306,7 @@ public class SocketTCP extends Thread {
* condição de erro.</p>
*
* <p>O método também trata timeouts e erros de I/O, removendo a conexão
* do {@link TcpConnectionManager} quando ela deixa de ser utilizável.</p>
* do {@link ConnectionManager} quando ela deixa de ser utilizável.</p>
*
* @param connection conexão pública da qual as mensagens serão recebidas.
*/
@@ -302,55 +314,35 @@ public class SocketTCP extends Thread {
while (running) {
try {
byte[] bytes = connection.receive();
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis)) {
Object object = ois.readObject();
if (object instanceof Message message) {
SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(message);
SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(bytes);
if (sysMessage == null) {
pluginManager.handlePublicMessage(message);
continue;
}
switch (sysMessage.getType()) {
case CONNECTION_CLOSED, INTERNAL_ERROR -> {
tcpConnectionManager.closeConnection(connection);
return;
}
case MESSAGE_REJECTED -> {
logger.log(Level.SEVERE, "Somehow sent something that was not an Message");
}
default -> {}
}
}
else {
SysInfoMessage.sendSystemInfo(
connection,
SysInfoType.MESSAGE_REJECTED,
"Public messages must be instances of Message"
);
if (sysMessage == null) {
for (Plugin plugin : main.getPlugins()) {
plugin.receiveMessage(bytes);
}
continue;
}
catch (ClassNotFoundException ex) {
SysInfoMessage.sendSystemInfo(
connection,
SysInfoType.INTERNAL_ERROR,
"class Message not found."
);
logger.log(Level.SEVERE, null, ex);
tcpConnectionManager.closeConnection(connection);
switch (sysMessage.getType()) {
case CONNECTION_CLOSED, INTERNAL_ERROR -> {
connectionManager.closeConnection(connection);
return;
}
case MESSAGE_REJECTED -> {
logger.log(Level.SEVERE, "Somehow sent something that was not an Message");
}
default -> {}
}
}
catch (SocketTimeoutException ex) {
if (connection.hasTimedOut()) {
tcpConnectionManager.closeConnection(connection, "Connection timeout");
connectionManager.closeConnection(connection, "Connection timeout");
return;
}
}
catch (IOException ex) {
tcpConnectionManager.closeConnection(connection);
connectionManager.closeConnection(connection);
}
}
}
@@ -365,36 +357,39 @@ public class SocketTCP extends Thread {
* do plugin e o fechamento da conexão.</p>
*
* @param connection conexão privada da qual os dados serão recebidos.
* @param plugin plugin responsável pelo processamento dos dados recebidos.
*/
private void privateConnectionReceiver(TcpConnection connection) {
while (running) {
try {
byte[] message = connection.receive();
SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(message);
private void privateConnectionReceiver(TcpConnection connection, Plugin plugin) {
if (plugin instanceof PrivateConnectionPlugin privatePlugin) {
while (running) {
try {
byte[] message = connection.receive();
SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(message);
if (sysMessage == null) {
pluginManager.handlePrivateMessage(message, connection.getReceiver());
continue;
}
switch (sysMessage.getType()) {
case CONNECTION_CLOSED, INTERNAL_ERROR -> {
pluginManager.handleDisconnection(connection, connection.getReceiver());
tcpConnectionManager.closeConnection(connection);
}
default -> {
if (sysMessage == null) {
privatePlugin.receiveBytes(connection, message);
continue;
}
switch (sysMessage.getType()) {
case CONNECTION_CLOSED, INTERNAL_ERROR -> {
privatePlugin.onSocketClosed(connection);
connectionManager.closeConnection(connection);
}
default -> {
continue;
}
}
}
}
catch (SocketTimeoutException ex) {
if (connection.hasTimedOut()) {
tcpConnectionManager.closeConnection(connection, "Connection timeout");
return;
catch (SocketTimeoutException ex) {
if (connection.hasTimedOut()) {
connectionManager.closeConnection(connection, "Connection timeout");
return;
}
}
catch (IOException ex) {
connectionManager.closeConnection(connection);
}
}
catch (IOException ex) {
tcpConnectionManager.closeConnection(connection);
}
}
}
@@ -426,7 +421,7 @@ public class SocketTCP extends Thread {
if (connection.hasTimedOut()) return;
}
catch (IOException ex) {
tcpConnectionManager.closeConnection(connection);
connectionManager.closeConnection(connection);
}
}
}
@@ -435,13 +430,13 @@ public class SocketTCP extends Thread {
* Encerra uma conexão TCP e registra o motivo informado.
*
* <p>Quando nenhuma descrição é fornecida, é utilizado um motivo padrão.
* O fechamento efetivo da conexão é delegado ao {@link TcpConnectionManager}.</p>
* O fechamento efetivo da conexão é delegado ao {@link ConnectionManager}.</p>
*
* @param connection conexão que será encerrada.
* @param description motivo do encerramento; pode ser {@code null}.
*/
public void disconnect(TcpConnection connection, String description) {
tcpConnectionManager.closeConnection(
connectionManager.closeConnection(
connection,
Objects.requireNonNullElse(description, "No reason provided")
);
@@ -474,7 +469,7 @@ public class SocketTCP extends Thread {
}
}
tcpConnectionManager.closeAllConnections("The peer must have closed the application or changed ports");
connectionManager.closeAllConnections("The peer must have closed the application or changed ports");
connectionExecutor.shutdownNow();
}
@@ -48,11 +48,4 @@ public class SysInfoMessage extends Message {
}
return null;
}
public static SysInfoMessage parseSystemInfo(Message message) {
if (message instanceof SysInfoMessage) {
return (SysInfoMessage) message;
}
return null;
}
}
+22 -46
View File
@@ -14,8 +14,6 @@ import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import pitiupi.control.ConnectionManager;
import pitiupi.control.PluginManager;
import pitiupi.net.HeartbeatMessage;
import pitiupi.net.Message;
import pitiupi.plugin.Plugin;
@@ -39,10 +37,7 @@ public class SocketUDP extends Thread {
private MulticastSocket multicastSocket;
private InetAddress address;
private ConnectionManager connectionManager;
private PluginManager pluginManager;
private MainWindow main;
private volatile boolean running = true;
public final static String INET_ADDR = "224.0.0.3";
@@ -52,26 +47,22 @@ public class SocketUDP extends Thread {
* <p>O socket é associado à porta da aplicação e ingressa no grupo
* multicast configurado.</p>
*
* @param connectionManager interface que gerencia toda conexão da aplicação.
* @param pluginManager interface que gerencia os plugins da conexão.
* @param main janela principal da aplicação.
*/
public SocketUDP(ConnectionManager connectionManager, PluginManager pluginManager) {
this.connectionManager = connectionManager;
this.pluginManager = pluginManager;
public SocketUDP(MainWindow main) {
this.main = main;
try {
this.address = InetAddress.getByName(SocketUDP.INET_ADDR);
multicastSocket = new MulticastSocket(connectionManager.getPort());
} catch (UnknownHostException ex) {
System.getLogger(SocketUDP.class.getName()).log(System.Logger.Level.ERROR, (String) null, ex);
}
try {
multicastSocket = new MulticastSocket(this.main.getPort());
multicastSocket.setSendBufferSize(256000);
multicastSocket.setReceiveBufferSize(256000);
multicastSocket.setReuseAddress(true);
multicastSocket.joinGroup(address);
}
catch (UnknownHostException ex) {
System.getLogger(SocketUDP.class.getName()).log(System.Logger.Level.ERROR, (String) null, ex);
}
catch (IOException ex) {
} catch (IOException ex) {
System.out.println("There is no socket connection. Sorry.");
System.out.println(ex);
}
@@ -80,22 +71,22 @@ public class SocketUDP extends Thread {
/**
* Envia uma mensagem para o grupo multicast da aplicação.
*
* @param msg mensagem a ser enviada.
* @param msg mensagem serializada a ser enviada.
* @throws IOException caso ocorra um erro durante o envio.
*/
public void sendMulticast(Message msg) throws IOException {
send(msg.toByteArray(), this.address);
send(msg, address);
}
/**
* Envia uma mensagem diretamente para um peer utilizando UDP.
*
* @param msg mensagem a ser enviada.
* @param msg mensagem serializada a ser enviada.
* @param destinationAddress endereço IP do peer destinatário.
* @throws IOException caso ocorra um erro durante o envio.
*/
public void sendUnicast(Message msg, InetAddress destinationAddress) throws IOException {
send(msg.toByteArray(), destinationAddress);
send(msg, destinationAddress);
}
/**
@@ -105,9 +96,10 @@ public class SocketUDP extends Thread {
* @param destinationAddress endereço de destino.
* @throws IOException caso ocorra um erro durante o envio.
*/
private void send(byte[] msg, InetAddress destinationAddress) throws IOException {
private void send(Message msg, InetAddress destinationAddress) throws IOException {
DatagramPacket msgPacket;
msgPacket = new DatagramPacket(msg, msg.length, destinationAddress, connectionManager.getPort());
byte[] buf = msg.toByteArray();
msgPacket = new DatagramPacket(buf, buf.length, destinationAddress, this.main.getPort());
multicastSocket.send(msgPacket);
}
@@ -152,19 +144,17 @@ public class SocketUDP extends Thread {
}
throw ex;
}
HeartbeatMessage heartbeat = tryParseHeartbeat(msgPacket.getData());
if (heartbeat != null) {
connectionManager.receiveHeartbeat(heartbeat, msgPacket.getAddress());
main.getHeartbeatManager().receiveHeartbeat(heartbeat, msgPacket.getAddress());
continue;
}
Message message = tryParseMessage(msgPacket.getData());
if (message == null) {
continue;
for (Plugin plugin : main.getPlugins()) {
System.out.println(msgPacket.getAddress().toString());
plugin.receiveMessage(msgPacket.getData());
}
System.out.println(msgPacket.getAddress().toString());
pluginManager.handlePublicMessage(message);
}
}
@@ -186,20 +176,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.
*/
+1 -1
View File
@@ -47,6 +47,6 @@ public interface Plugin {
*
* @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 void receivePrivateConnection(TcpConnection connection);
public void receiveBytes(byte[] bytes);
public void receiveBytes(TcpConnection connection, byte[] bytes);
public void onSocketClosed(TcpConnection connection);
}