Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23559dcc06 | ||
|
|
fa4ee046b1 | ||
|
|
0c71a85cba | ||
|
|
e7c8983775 | ||
|
|
0ec3129a22 | ||
|
|
ba2f41daf7 | ||
|
|
57059c3ef0 | ||
|
|
b5bbd1df2d | ||
|
|
93ac292f72 | ||
|
|
b610ec20e1 | ||
|
|
4461772ebf | ||
|
|
0d5a4dbe75 | ||
|
|
bbb1ceea23 | ||
|
|
7d9ca4ca71 | ||
|
|
1fcc03d9be |
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.
@@ -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>
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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.
@@ -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);
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,8 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.GUI;
|
package pitiupi.GUI;
|
||||||
|
|
||||||
import pitiupi.net.SocketTCP;
|
import pitiupi.net.tcp.SocketTCP;
|
||||||
import pitiupi.net.SocketUDP;
|
import pitiupi.net.udp.SocketUDP;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import javax.swing.JMenu;
|
import javax.swing.JMenu;
|
||||||
@@ -44,7 +44,9 @@ public class MainWindow extends javax.swing.JFrame {
|
|||||||
private SocketTCP socketTCP;
|
private SocketTCP socketTCP;
|
||||||
|
|
||||||
private String userName;
|
private String userName;
|
||||||
private int port;
|
private int port;
|
||||||
|
|
||||||
|
private String pitiupiIdentifier;
|
||||||
|
|
||||||
private PluginLoader pluginManager;
|
private PluginLoader pluginManager;
|
||||||
private final List<Plugin> plugins;
|
private final List<Plugin> plugins;
|
||||||
@@ -58,6 +60,7 @@ public class MainWindow extends javax.swing.JFrame {
|
|||||||
public MainWindow(String userName, int port) {
|
public MainWindow(String userName, int port) {
|
||||||
this.userName = userName;
|
this.userName = userName;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
|
this.pitiupiIdentifier = "Pitiupi.Alice.2026";
|
||||||
this.menuBar = new MenuBar(this);
|
this.menuBar = new MenuBar(this);
|
||||||
this.plugins = new ArrayList<>();
|
this.plugins = new ArrayList<>();
|
||||||
this.initComponents();
|
this.initComponents();
|
||||||
@@ -126,6 +129,10 @@ public class MainWindow extends javax.swing.JFrame {
|
|||||||
public String getUserName(){
|
public String getUserName(){
|
||||||
return this.userName;
|
return this.userName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getIdentifier(){
|
||||||
|
return this.pitiupiIdentifier;
|
||||||
|
}
|
||||||
|
|
||||||
public void addMenu(JMenu menu) {
|
public void addMenu(JMenu menu) {
|
||||||
this.menuBar.addPlugin(menu);
|
this.menuBar.addPlugin(menu);
|
||||||
@@ -139,7 +146,7 @@ public class MainWindow extends javax.swing.JFrame {
|
|||||||
return this.socketUDP;
|
return this.socketUDP;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SocketTCP getSocketTCP() {
|
public SocketTCP getSocketTCP() {
|
||||||
return this.socketTCP;
|
return this.socketTCP;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ public class HeartbeatManager {
|
|||||||
private void announce() {
|
private void announce() {
|
||||||
try {
|
try {
|
||||||
HeartbeatMessage msg = new HeartbeatMessage(mainWindow.getUserName(), instanceId);
|
HeartbeatMessage msg = new HeartbeatMessage(mainWindow.getUserName(), instanceId);
|
||||||
mainWindow.getSocketUDP().sendMulticast(msg.toByteArray());
|
mainWindow.getSocketUDP().sendMulticast(msg);
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
Logger.getLogger(HeartbeatManager.class.getName()).log(Level.WARNING, "Falha ao enviar heartbeat", ex);
|
Logger.getLogger(HeartbeatManager.class.getName()).log(Level.WARNING, "Falha ao enviar heartbeat", ex);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
package pitiupi.net;
|
package pitiupi.net;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mensagem utilizada para sinalizar a presença de um usuário na rede.
|
* Mensagem utilizada para sinalizar a presença de um usuário na rede.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,244 +0,0 @@
|
|||||||
package pitiupi.net;
|
|
||||||
|
|
||||||
import pitiupi.GUI.MainWindow;
|
|
||||||
import pitiupi.control.PeerInfo;
|
|
||||||
import pitiupi.control.PeerListener;
|
|
||||||
import pitiupi.plugin.Plugin;
|
|
||||||
|
|
||||||
import java.io.*;
|
|
||||||
import java.net.*;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gerencia a comunicação TCP da aplicação.
|
|
||||||
*
|
|
||||||
* <p>Mantém conexões persistentes com os peers e reutiliza essas conexões
|
|
||||||
* para o envio de mensagens. As mensagens recebidas são encaminhadas aos
|
|
||||||
* plugins, que são responsáveis por interpretá-las.</p>
|
|
||||||
*
|
|
||||||
* <p>Novas conexões são aceitas pelo servidor e cada conexão possui uma
|
|
||||||
* tarefa própria para receber mensagens, permitindo que múltiplas conexões
|
|
||||||
* sejam mantidas simultaneamente.</p>
|
|
||||||
*
|
|
||||||
* <p>As conexões são associadas aos endereços dos peers e podem ser
|
|
||||||
* encerradas quando um peer deixa de estar ativo.</p>
|
|
||||||
*
|
|
||||||
* @author Gustavo
|
|
||||||
*/
|
|
||||||
public class SocketTCP extends Thread implements PeerListener {
|
|
||||||
private final ExecutorService connectionExecutor = Executors.newCachedThreadPool();
|
|
||||||
private final Map<InetAddress, TcpConnection> connections;
|
|
||||||
private ServerSocket serverSocket;
|
|
||||||
private InetAddress address;
|
|
||||||
|
|
||||||
private final MainWindow main;
|
|
||||||
|
|
||||||
private volatile boolean running = true;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cria o servidor TCP da aplicação.
|
|
||||||
*
|
|
||||||
* <p>O servidor utiliza a porta definida pela aplicação e inicia sem
|
|
||||||
* estabelecer conexões com os peers. As conexões são criadas conforme
|
|
||||||
* necessário durante o envio ou recebidas de outros peers.</p>
|
|
||||||
*
|
|
||||||
* @param main janela principal da aplicação.
|
|
||||||
*/
|
|
||||||
public SocketTCP(MainWindow main) {
|
|
||||||
this.main = main;
|
|
||||||
connections = new ConcurrentHashMap<>();
|
|
||||||
try {
|
|
||||||
serverSocket = new ServerSocket(main.getPort());
|
|
||||||
address = InetAddress.getByName(InetAddress.getLocalHost().getHostAddress());
|
|
||||||
} catch (IOException ex) {
|
|
||||||
System.out.println("There is no socket connection. Sorry.");
|
|
||||||
System.out.println(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Envia uma mensagem TCP para um peer.
|
|
||||||
*
|
|
||||||
* <p>Uma conexão existente com o peer é reutilizada. Caso não exista uma
|
|
||||||
* conexão válida, uma nova conexão é criada e adicionada ao conjunto de
|
|
||||||
* conexões ativas.</p>
|
|
||||||
*
|
|
||||||
* @param msg mensagem serializada a ser enviada.
|
|
||||||
* @param destinationAddress endereço IP do peer destinatário.
|
|
||||||
*/
|
|
||||||
public void send(byte[] msg, InetAddress destinationAddress) {
|
|
||||||
try {
|
|
||||||
if (destinationAddress.equals(address)) {
|
|
||||||
throw new IllegalArgumentException("Destination address cannot be the same as the original address.");
|
|
||||||
}
|
|
||||||
TcpConnection connec tion;
|
|
||||||
|
|
||||||
synchronized (connections) {
|
|
||||||
connection = connections.get(destinationAddress);
|
|
||||||
|
|
||||||
if (connection == null || connection.isClosed()) {
|
|
||||||
Socket socket = new Socket(destinationAddress, main.getPort());
|
|
||||||
|
|
||||||
connection = new TcpConnection(socket);
|
|
||||||
|
|
||||||
connections.put(destinationAddress, connection);
|
|
||||||
|
|
||||||
startReceiver(destinationAddress, connection);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connection.send(msg);
|
|
||||||
|
|
||||||
} catch (IOException ex) {
|
|
||||||
System.out.println("Could not send TCP message.");
|
|
||||||
System.out.println(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aguarda e aceita novas conexões TCP.
|
|
||||||
*
|
|
||||||
* <p>Cada conexão aceita é associada ao endereço do peer e registrada para
|
|
||||||
* que possa ser utilizada tanto para recepção quanto para envio de
|
|
||||||
* mensagens.</p>
|
|
||||||
*/
|
|
||||||
private void receive() {
|
|
||||||
while (running) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Socket socket = serverSocket.accept();
|
|
||||||
|
|
||||||
InetAddress address = socket.getInetAddress();
|
|
||||||
|
|
||||||
TcpConnection connection = new TcpConnection(socket);
|
|
||||||
|
|
||||||
TcpConnection oldConnection = connections.put(address, connection);
|
|
||||||
|
|
||||||
if (oldConnection != null) {
|
|
||||||
oldConnection.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
startReceiver(address, connection);
|
|
||||||
|
|
||||||
} catch (IOException ex) {
|
|
||||||
|
|
||||||
if (!running) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("Error accepting TCP connection.");
|
|
||||||
System.out.println(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inicia a recepção de mensagens de uma conexão TCP.
|
|
||||||
*
|
|
||||||
* <p>A recepção é executada de forma independente para que uma conexão
|
|
||||||
* não impeça a aceitação ou o processamento de outras conexões.</p>
|
|
||||||
*
|
|
||||||
* <p>Cada mensagem recebida é encaminhada aos plugins da aplicação.</p>
|
|
||||||
*
|
|
||||||
* @param address endereço do peer associado à conexão.
|
|
||||||
* @param connection conexão TCP utilizada para a comunicação.
|
|
||||||
*/
|
|
||||||
private void startReceiver(InetAddress address, TcpConnection connection) {
|
|
||||||
connectionExecutor.submit(() -> {
|
|
||||||
try {
|
|
||||||
while (running) {
|
|
||||||
byte[] message = connection.receive();
|
|
||||||
|
|
||||||
for (Plugin plugin : main.getPlugins()) {
|
|
||||||
plugin.receiveMessage(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (IOException ex) {
|
|
||||||
System.out.println(
|
|
||||||
"Connection with " + address.getHostAddress() + " closed."
|
|
||||||
);
|
|
||||||
|
|
||||||
} finally {
|
|
||||||
connections.remove(address, connection);
|
|
||||||
|
|
||||||
try {
|
|
||||||
connection.close();
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inicia o processo de recepção de conexões TCP.
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
receive();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encerra o servidor TCP e as conexões associadas.
|
|
||||||
*
|
|
||||||
* <p>As conexões existentes são encerradas e o servidor deixa
|
|
||||||
* de aceitar novas conexões.</p>
|
|
||||||
*/
|
|
||||||
public void close() {
|
|
||||||
running = false;
|
|
||||||
|
|
||||||
if (serverSocket != null) {
|
|
||||||
try {
|
|
||||||
serverSocket.close();
|
|
||||||
} catch (IOException _) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (TcpConnection connection : connections.values()) {
|
|
||||||
try {
|
|
||||||
connection.close();
|
|
||||||
} catch (IOException _) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connections.clear();
|
|
||||||
|
|
||||||
connectionExecutor.shutdownNow();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Atualiza as conexões de acordo com os peers atualmente ativos.
|
|
||||||
*
|
|
||||||
* <p>Conexões associadas a peers que não estão mais ativos são encerradas
|
|
||||||
* e removidas.</p>
|
|
||||||
*
|
|
||||||
* @param peers lista atualizada de peers ativos.
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onPeersChanged(List<PeerInfo> peers) {
|
|
||||||
Set<InetAddress> activePeers = peers.stream()
|
|
||||||
.map(PeerInfo::getAddress)
|
|
||||||
.collect(Collectors.toSet());
|
|
||||||
|
|
||||||
for (InetAddress address : connections.keySet()) {
|
|
||||||
if (!activePeers.contains(address)) {
|
|
||||||
|
|
||||||
TcpConnection connection = connections.remove(address);
|
|
||||||
if (connection != null) {
|
|
||||||
try {
|
|
||||||
connection.close();
|
|
||||||
} catch (IOException e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
package pitiupi.net;
|
|
||||||
|
|
||||||
import java.io.DataInputStream;
|
|
||||||
import java.io.DataOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.Socket;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Representa uma conexão TCP persistente com um peer.
|
|
||||||
*
|
|
||||||
* <p>Encapsula o socket e os streams utilizados para enviar e receber
|
|
||||||
* mensagens. Também é responsável pelo framing das mensagens, permitindo
|
|
||||||
* que várias mensagens sejam transmitidas pela mesma conexão.</p>
|
|
||||||
*
|
|
||||||
* @author Gustavo
|
|
||||||
*/
|
|
||||||
class TcpConnection {
|
|
||||||
|
|
||||||
private final Socket socket;
|
|
||||||
private final DataInputStream input;
|
|
||||||
private final DataOutputStream output;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cria uma conexão a partir de um socket existente.
|
|
||||||
*
|
|
||||||
* @param socket socket TCP utilizado pela conexão.
|
|
||||||
* @throws IOException caso não seja possível obter os streams do socket.
|
|
||||||
*/
|
|
||||||
public TcpConnection(Socket socket) throws IOException {
|
|
||||||
this.socket = socket;
|
|
||||||
this.input = new DataInputStream(socket.getInputStream());
|
|
||||||
this.output = new DataOutputStream(socket.getOutputStream());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Envia uma mensagem pela conexão.
|
|
||||||
*
|
|
||||||
* <p>A mensagem é precedida por seu tamanho para permitir que o receptor
|
|
||||||
* identifique o limite entre mensagens transmitidas pela mesma conexão.</p>
|
|
||||||
*
|
|
||||||
* @param message mensagem serializada a ser enviada.
|
|
||||||
* @throws IOException caso ocorra um erro durante o envio.
|
|
||||||
*/
|
|
||||||
public void send(byte[] message) throws IOException {
|
|
||||||
synchronized (output) {
|
|
||||||
output.writeInt(message.length);
|
|
||||||
output.write(message);
|
|
||||||
output.flush();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Recebe uma mensagem completa da conexão.
|
|
||||||
*
|
|
||||||
* <p>O tamanho da mensagem é lido primeiro e, em seguida, os dados
|
|
||||||
* correspondentes são recebidos.</p>
|
|
||||||
*
|
|
||||||
* @return mensagem recebida.
|
|
||||||
* @throws IOException caso ocorra um erro durante a recepção.
|
|
||||||
*/
|
|
||||||
public byte[] receive() throws IOException {
|
|
||||||
int length = input.readInt();
|
|
||||||
|
|
||||||
if (length < 0) {
|
|
||||||
throw new IOException("Invalid message length.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return input.readNBytes(length);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifica se o socket da conexão está fechado.
|
|
||||||
*
|
|
||||||
* @return {@code true} caso o socket esteja fechado.
|
|
||||||
*/
|
|
||||||
public boolean isClosed() {
|
|
||||||
return socket.isClosed();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encerra a conexão TCP.
|
|
||||||
*
|
|
||||||
* @throws IOException caso ocorra um erro ao fechar o socket.
|
|
||||||
*/
|
|
||||||
public void close() throws IOException {
|
|
||||||
socket.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.net.Message;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fábrica responsável pela criação e configuração de conexões TCP.
|
||||||
|
*
|
||||||
|
* <p>Esta classe centraliza o estabelecimento de conexões de saída e a
|
||||||
|
* configuração de conexões recebidas. Antes de uma conexão ser considerada
|
||||||
|
* válida, é realizado um handshake entre os peers para identificar o remetente,
|
||||||
|
* o destinatário e se a conexão é privada.</p>
|
||||||
|
*
|
||||||
|
* <p>Durante o handshake é utilizado um timeout menor, definido por
|
||||||
|
* {@link #HANDSHAKE_TIMEOUT}. Após a validação bem-sucedida, a conexão passa
|
||||||
|
* a utilizar o timeout padrão definido por {@link #STANDARD_TIMEOUT}.</p>
|
||||||
|
*/
|
||||||
|
public class ConnectionFactory {
|
||||||
|
private static final int HANDSHAKE_TIMEOUT = 5000;
|
||||||
|
private static final int STANDARD_TIMEOUT = 300_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria uma conexão TCP de saída com o peer de destino e realiza o handshake
|
||||||
|
* necessário para validá-la.
|
||||||
|
*
|
||||||
|
* <p>A conexão é configurada com os identificadores do remetente e do
|
||||||
|
* destinatário e com o tipo indicado pelo parâmetro {@code isPrivate}.
|
||||||
|
* Após o estabelecimento do socket, o método envia um
|
||||||
|
* {@link HandshakeMessage} e aguarda uma resposta válida.</p>
|
||||||
|
*
|
||||||
|
* <p>Se o handshake for validado com sucesso, o timeout da conexão é
|
||||||
|
* alterado de {@link #HANDSHAKE_TIMEOUT} para {@link #STANDARD_TIMEOUT}
|
||||||
|
* e a conexão é retornada. Caso contrário, {@code null} é retornado.</p>
|
||||||
|
*
|
||||||
|
* @param address endereço IP do peer de destino.
|
||||||
|
* @param port porta TCP na qual o peer de destino está aguardando conexões.
|
||||||
|
* @param sender identificador do remetente da conexão.
|
||||||
|
* @param receiver identificador do destinatário da conexão.
|
||||||
|
* @param isPrivate {@code true} se a conexão deve ser privada;
|
||||||
|
* {@code false} se deve ser pública.
|
||||||
|
* @return a conexão TCP estabelecida e validada ou {@code null} caso
|
||||||
|
* não seja possível estabelecer ou validar a conexão.
|
||||||
|
*/
|
||||||
|
public static TcpConnection createConnection(InetAddress address, int port, String sender, String receiver, boolean isPrivate) {
|
||||||
|
try {
|
||||||
|
TcpConnection connection;
|
||||||
|
|
||||||
|
Socket socket = new Socket(address, port);
|
||||||
|
connection = new TcpConnection(socket);
|
||||||
|
connection.setSender(sender);
|
||||||
|
connection.setReceiver(receiver);
|
||||||
|
connection.setPrivate(isPrivate);
|
||||||
|
|
||||||
|
HandshakeMessage handshake = new HandshakeMessage(isPrivate, sender, receiver);
|
||||||
|
|
||||||
|
connection.send(handshake.toByteArray());
|
||||||
|
HandshakeMessage handshakeResponse = validateConnection(connection);
|
||||||
|
|
||||||
|
if (handshakeResponse == null) return null;
|
||||||
|
|
||||||
|
connection.setTimeout(STANDARD_TIMEOUT);
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configura uma conexão TCP recebida e valida o handshake enviado pelo
|
||||||
|
* peer remoto.
|
||||||
|
*
|
||||||
|
* <p>O handshake recebido é utilizado para obter e configurar os
|
||||||
|
* identificadores do remetente e do destinatário, bem como o tipo da
|
||||||
|
* conexão. Após a validação bem-sucedida, o timeout da conexão é alterado
|
||||||
|
* para {@link #STANDARD_TIMEOUT}.</p>
|
||||||
|
*
|
||||||
|
* <p>O {@link Socket} recebido deve representar uma conexão TCP já aceita
|
||||||
|
* pelo servidor.</p>
|
||||||
|
*
|
||||||
|
* @param socket socket TCP correspondente à conexão recebida.
|
||||||
|
* @return a conexão TCP configurada e validada ou {@code null} caso
|
||||||
|
* o handshake seja inválido ou não possa ser processado.
|
||||||
|
*/
|
||||||
|
public static TcpConnection receiveConnection(Socket socket) {
|
||||||
|
try {
|
||||||
|
TcpConnection connection;
|
||||||
|
|
||||||
|
connection = new TcpConnection(socket);
|
||||||
|
|
||||||
|
HandshakeMessage handshake = validateConnection(connection);
|
||||||
|
|
||||||
|
if (handshake == null) return null;
|
||||||
|
|
||||||
|
|
||||||
|
connection.send(handshake.createResponse().toByteArray());
|
||||||
|
|
||||||
|
connection.setSender(handshake.getSender());
|
||||||
|
connection.setReceiver(handshake.getReceiver());
|
||||||
|
connection.setPrivate(handshake.isPrivate());
|
||||||
|
|
||||||
|
connection.setTimeout(STANDARD_TIMEOUT);
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aguarda e valida a mensagem de handshake de uma conexão TCP.
|
||||||
|
*
|
||||||
|
* <p>Durante a validação, a conexão utiliza {@link #HANDSHAKE_TIMEOUT}
|
||||||
|
* como limite para o recebimento do handshake. A mensagem recebida deve
|
||||||
|
* ser uma instância de {@link Message} e, especificamente, de
|
||||||
|
* {@link HandshakeMessage}. Mensagens de sistema ou mensagens de outros
|
||||||
|
* tipos são rejeitadas.</p>
|
||||||
|
*
|
||||||
|
* <p>Quando o handshake é recebido, seus campos de remetente e destinatário
|
||||||
|
* são validados por {@link #validateHandshake(HandshakeMessage, TcpConnection)}.
|
||||||
|
* Caso a validação seja bem-sucedida, o próprio handshake é retornado.</p>
|
||||||
|
*
|
||||||
|
* <p>Em caso de timeout, mensagem inválida ou erro durante o processamento,
|
||||||
|
* uma mensagem de sistema apropriada pode ser enviada ao peer e
|
||||||
|
* {@code null} é retornado.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão TCP da qual o handshake será recebido.
|
||||||
|
* @return o {@link HandshakeMessage} validado ou {@code null} caso o
|
||||||
|
* handshake não seja recebido ou seja inválido.
|
||||||
|
*/
|
||||||
|
private static HandshakeMessage validateConnection(TcpConnection connection) {
|
||||||
|
try {
|
||||||
|
connection.setTimeout(HANDSHAKE_TIMEOUT);
|
||||||
|
byte[] bytes = connection.receive();
|
||||||
|
|
||||||
|
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bis);
|
||||||
|
|
||||||
|
Object object = ois.readObject();
|
||||||
|
|
||||||
|
if (object instanceof Message message) {
|
||||||
|
SysInfoMessage sysInfo = SysInfoMessage.parseSystemInfo(bytes);
|
||||||
|
if (sysInfo != null) return null;
|
||||||
|
|
||||||
|
|
||||||
|
if (message instanceof HandshakeMessage handshake) {
|
||||||
|
return (validateHandshake(handshake, connection)) ? handshake : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SysInfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
SysInfoType.CONNECTION_REJECTED,
|
||||||
|
"The message was not from an allowed type."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (SocketTimeoutException ex) {
|
||||||
|
SysInfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
SysInfoType.CONNECTION_REJECTED,
|
||||||
|
"No handshake was received within the allowed time."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (ClassNotFoundException | IOException ex) {
|
||||||
|
Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
|
|
||||||
|
SysInfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
SysInfoType.INTERNAL_ERROR,
|
||||||
|
"The server could not process the handshake."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valida os identificadores presentes em uma mensagem de handshake.
|
||||||
|
*
|
||||||
|
* <p>O remetente e o destinatário devem estar presentes e não podem ser
|
||||||
|
* vazios ou conter apenas espaços em branco. Quando um dos identificadores
|
||||||
|
* é inválido, uma mensagem de rejeição é enviada ao peer e a validação
|
||||||
|
* falha.</p>
|
||||||
|
*
|
||||||
|
* @param handshake mensagem de handshake a ser validada.
|
||||||
|
* @param connection conexão associada ao handshake, utilizada para enviar
|
||||||
|
* uma mensagem de rejeição quando necessário.
|
||||||
|
* @return {@code true} se os identificadores do remetente e do destinatário
|
||||||
|
* forem válidos; {@code false} caso contrário.
|
||||||
|
*/
|
||||||
|
private static boolean validateHandshake(HandshakeMessage handshake, TcpConnection connection) {
|
||||||
|
String sender = handshake.getSender();
|
||||||
|
String receiver = handshake.getReceiver();
|
||||||
|
|
||||||
|
if (sender == null || sender.isBlank()) {
|
||||||
|
SysInfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
SysInfoType.CONNECTION_REJECTED,
|
||||||
|
"Invalid Sender: " + sender + "."
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (receiver == null || receiver.isBlank()) {
|
||||||
|
SysInfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
SysInfoType.CONNECTION_REJECTED,
|
||||||
|
"Invalid Receiver: " + receiver + "."
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.control.PeerInfo;
|
||||||
|
import pitiupi.control.PeerListener;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gerencia as conexões TCP estabelecidas com os peers da aplicação.
|
||||||
|
*
|
||||||
|
* <p>As conexões públicas são armazenadas individualmente por endereço IP,
|
||||||
|
* enquanto as conexões privadas são agrupadas por endereço, permitindo que
|
||||||
|
* um mesmo peer mantenha múltiplas conexões privadas simultaneamente.</p>
|
||||||
|
*
|
||||||
|
* <p>Além de manter o registro das conexões ativas, esta classe é responsável
|
||||||
|
* por encerrá-las quando necessário e por remover do gerenciamento as
|
||||||
|
* conexões que forem fechadas. Também acompanha as alterações na lista de
|
||||||
|
* peers ativos para encerrar conexões associadas a peers que deixaram de
|
||||||
|
* estar disponíveis.</p>
|
||||||
|
*/
|
||||||
|
class ConnectionManager implements PeerListener {
|
||||||
|
private final Logger logger;
|
||||||
|
private final Map<InetAddress, TcpConnection> publicConnections;
|
||||||
|
private final Map<InetAddress, List<TcpConnection>> privateConnections;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria um gerenciador de conexões TCP vazio.
|
||||||
|
*/
|
||||||
|
public ConnectionManager() {
|
||||||
|
publicConnections = new ConcurrentHashMap<>();
|
||||||
|
privateConnections = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
logger = Logger.getLogger(getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtém a conexão pública registrada para um determinado peer.
|
||||||
|
*
|
||||||
|
* @param address endereço IP do peer.
|
||||||
|
* @return a conexão pública registrada para o endereço ou {@code null}
|
||||||
|
* caso não exista uma conexão pública registrada.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public TcpConnection getPublicConnection(InetAddress address) {
|
||||||
|
return publicConnections.get(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registra uma conexão privada associada a um peer.
|
||||||
|
*
|
||||||
|
* <p>Um mesmo peer pode possuir múltiplas conexões privadas. Por isso,
|
||||||
|
* as conexões são armazenadas em uma lista associada ao endereço do
|
||||||
|
* peer.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão privada a ser registrada.
|
||||||
|
*/
|
||||||
|
public void addPrivateConnection(TcpConnection connection) {
|
||||||
|
List<TcpConnection> connections =
|
||||||
|
privateConnections.computeIfAbsent(connection.getAddress(), _ -> new ArrayList<>());
|
||||||
|
|
||||||
|
synchronized (connections) {
|
||||||
|
connections.add(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registra uma conexão pública associada a um peer.
|
||||||
|
*
|
||||||
|
* <p>Cada peer pode possuir apenas uma conexão pública registrada.
|
||||||
|
* Quando já existe uma conexão pública para o endereço da nova conexão,
|
||||||
|
* a conexão anterior é encerrada e substituída pela nova.</p>
|
||||||
|
*
|
||||||
|
* @param connection nova conexão pública a ser registrada.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void addPublicConnection(TcpConnection connection) {
|
||||||
|
TcpConnection oldConnection = publicConnections.put(connection.getAddress(), connection);
|
||||||
|
if (oldConnection != null && oldConnection != connection) {
|
||||||
|
closeConnection(oldConnection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem de encerramento ao peer e fecha a conexão.
|
||||||
|
*
|
||||||
|
* <p>A mensagem enviada informa o motivo do encerramento antes que a
|
||||||
|
* conexão seja removida do gerenciamento e fechada.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão TCP a ser encerrada.
|
||||||
|
* @param reason motivo do encerramento que será informado ao peer.
|
||||||
|
*/
|
||||||
|
public void closeConnection(TcpConnection connection, String reason) {
|
||||||
|
SysInfoMessage.sendSystemInfo(connection, SysInfoType.CONNECTION_CLOSED, reason);
|
||||||
|
closeConnection(connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove uma conexão do gerenciamento e encerra seu socket.
|
||||||
|
*
|
||||||
|
* <p>Para conexões privadas, a conexão é removida da lista associada ao
|
||||||
|
* endereço do peer. Caso essa seja a última conexão privada do endereço,
|
||||||
|
* a lista também é removida do mapa.</p>
|
||||||
|
*
|
||||||
|
* <p>Para conexões públicas, a conexão é removida do mapa somente se
|
||||||
|
* ainda for a conexão registrada para seu endereço.</p>
|
||||||
|
*
|
||||||
|
* <p>Se a conexão já estiver fechada ou for {@code null}, nenhuma ação
|
||||||
|
* adicional de fechamento é realizada.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão TCP a ser removida e encerrada.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void closeConnection(TcpConnection connection) {
|
||||||
|
if (connection == null) return;
|
||||||
|
if (connection.isPrivate()) {
|
||||||
|
List<TcpConnection> connections = privateConnections.get(connection.getAddress());
|
||||||
|
|
||||||
|
if (connections != null) {
|
||||||
|
synchronized (connections) {
|
||||||
|
connections.remove(connection);
|
||||||
|
|
||||||
|
if (connections.isEmpty()) privateConnections.remove(connection.getAddress(), connections);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else publicConnections.remove(connection.getAddress(), connection);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!connection.isClosed()) {
|
||||||
|
connection.close();
|
||||||
|
}
|
||||||
|
} catch (IOException ex) {
|
||||||
|
logger.log(Level.SEVERE, "Error closing TCP connection", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem de encerramento para todas as conexões de um peer
|
||||||
|
* e, em seguida, fecha essas conexões.
|
||||||
|
*
|
||||||
|
* @param address endereço IP do peer cujas conexões serão encerradas.
|
||||||
|
* @param reason motivo do encerramento informado ao peer.
|
||||||
|
*/
|
||||||
|
public void closeByAdress(InetAddress address, String reason) {
|
||||||
|
List<TcpConnection> connections = privateConnections.get(address);
|
||||||
|
for (TcpConnection connection : connections) {
|
||||||
|
SysInfoMessage.sendSystemInfo(connection, SysInfoType.CONNECTION_CLOSED, reason);
|
||||||
|
}
|
||||||
|
closeByAdress(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha e remove todas as conexões associadas a um determinado endereço.
|
||||||
|
*
|
||||||
|
* <p>Tanto a conexão pública quanto todas as conexões privadas associadas
|
||||||
|
* ao endereço são encerradas e removidas do gerenciamento.</p>
|
||||||
|
*
|
||||||
|
* @param address endereço IP do peer cujas conexões serão encerradas.
|
||||||
|
*/
|
||||||
|
public void closeByAdress(InetAddress address) {
|
||||||
|
TcpConnection publicConnection = publicConnections.remove(address);
|
||||||
|
|
||||||
|
if (publicConnection != null) {
|
||||||
|
try {
|
||||||
|
publicConnection.close();
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
logger.log(Level.SEVERE, "Error closing TCP connection", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
List<TcpConnection> connections = privateConnections.remove(address);
|
||||||
|
|
||||||
|
if (connections != null) {
|
||||||
|
synchronized (connections) {
|
||||||
|
for (TcpConnection connection : connections) {
|
||||||
|
try {
|
||||||
|
connection.close();
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
logger.log(Level.SEVERE, "Error closing TCP connection", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
connections.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem de encerramento para todas as conexões privadas
|
||||||
|
* gerenciadas e, em seguida, fecha todas elas.
|
||||||
|
*
|
||||||
|
* @param reason motivo do encerramento informado aos peers.
|
||||||
|
*/
|
||||||
|
public void closeAllConnections(String reason) {
|
||||||
|
for (List<TcpConnection> connections : privateConnections.values()) {
|
||||||
|
for (TcpConnection connection : connections) {
|
||||||
|
SysInfoMessage.sendSystemInfo(connection, SysInfoType.CONNECTION_CLOSED, reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
closeAllConnections();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha e remove todas as conexões públicas e privadas gerenciadas.
|
||||||
|
*
|
||||||
|
* <p>Após a execução, não devem permanecer conexões registradas nos
|
||||||
|
* mapas de conexões deste gerenciador.</p>
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void closeAllConnections() {
|
||||||
|
for (TcpConnection connection : publicConnections.values()) {
|
||||||
|
closeConnection(connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized (privateConnections) {
|
||||||
|
for (List<TcpConnection> connectionsList : privateConnections.values()) {
|
||||||
|
for (TcpConnection connection : connectionsList) {
|
||||||
|
closeConnection(connection);
|
||||||
|
}
|
||||||
|
privateConnections.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atualiza as conexões de acordo com os peers atualmente ativos.
|
||||||
|
*
|
||||||
|
* <p>Os endereços presentes na lista de peers são utilizados como
|
||||||
|
* referência para determinar quais conexões ainda devem permanecer
|
||||||
|
* ativas. Conexões públicas e privadas associadas a endereços que não
|
||||||
|
* estão mais presentes na lista de peers são encerradas e removidas.</p>
|
||||||
|
*
|
||||||
|
* @param peers lista atualizada de peers ativos.
|
||||||
|
*/
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onPeersChanged(List<PeerInfo> peers) {
|
||||||
|
Set<InetAddress> activePeers = peers.stream().map(PeerInfo::getAddress).collect(Collectors.toSet());
|
||||||
|
|
||||||
|
for (InetAddress address : publicConnections.keySet()) {
|
||||||
|
if (!activePeers.contains(address)) {
|
||||||
|
closeByAdress(address);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (InetAddress address : privateConnections.keySet()) {
|
||||||
|
if (!activePeers.contains(address)) {
|
||||||
|
closeByAdress(address);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.net.Message;
|
||||||
|
|
||||||
|
class HandshakeMessage extends Message {
|
||||||
|
private final boolean isPrivate;
|
||||||
|
private final String sender;
|
||||||
|
private final String receiver;
|
||||||
|
|
||||||
|
|
||||||
|
public HandshakeMessage(boolean isPrivate, String sender, String receiver) {
|
||||||
|
this.isPrivate = isPrivate;
|
||||||
|
this.sender = sender;
|
||||||
|
this.receiver = receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPrivate() {
|
||||||
|
return isPrivate;
|
||||||
|
}
|
||||||
|
public String getSender() {
|
||||||
|
return sender;
|
||||||
|
}
|
||||||
|
public String getReceiver() {
|
||||||
|
return receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public HandshakeMessage createResponse() {
|
||||||
|
return new HandshakeMessage(isPrivate, receiver, sender);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,476 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.GUI.MainWindow;
|
||||||
|
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;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gerencia a comunicação TCP da aplicação.
|
||||||
|
*
|
||||||
|
* <p>Mantém conexões persistentes com os peers e reutiliza essas conexões
|
||||||
|
* para o envio de mensagens. As mensagens recebidas são encaminhadas aos
|
||||||
|
* plugins, que são responsáveis por interpretá-las.</p>
|
||||||
|
*
|
||||||
|
* <p>Novas conexões são aceitas pelo servidor e cada conexão possui uma
|
||||||
|
* tarefa própria para receber mensagens, permitindo que múltiplas conexões
|
||||||
|
* sejam mantidas simultaneamente.</p>
|
||||||
|
*
|
||||||
|
* <p>As conexões são associadas aos endereços dos peers e podem ser
|
||||||
|
* encerradas quando um peer deixa de estar ativo.</p>
|
||||||
|
*
|
||||||
|
* @author Gustavo
|
||||||
|
*/
|
||||||
|
public class SocketTCP extends Thread {
|
||||||
|
private final Logger logger;
|
||||||
|
|
||||||
|
private final ExecutorService connectionExecutor = Executors.newCachedThreadPool();
|
||||||
|
|
||||||
|
private final ConnectionManager connectionManager;
|
||||||
|
|
||||||
|
private ServerSocket serverSocket;
|
||||||
|
private InetAddress address;
|
||||||
|
|
||||||
|
private final MainWindow main;
|
||||||
|
|
||||||
|
private volatile boolean running = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria o servidor TCP da aplicação.
|
||||||
|
*
|
||||||
|
* <p>O servidor é criado na porta definida pela aplicação. As conexões
|
||||||
|
* com os peers são estabelecidas sob demanda durante o envio ou aceitas
|
||||||
|
* quando iniciadas por outros peers.</p>
|
||||||
|
*
|
||||||
|
* @param main janela principal da aplicação, usada para obter a porta,
|
||||||
|
* o identificador local e os plugins disponíveis.
|
||||||
|
*/
|
||||||
|
public SocketTCP(MainWindow main) {
|
||||||
|
this.main = main;
|
||||||
|
logger = Logger.getLogger(getClass().getName());
|
||||||
|
connectionManager = new ConnectionManager();
|
||||||
|
try {
|
||||||
|
serverSocket = new ServerSocket(main.getPort());
|
||||||
|
address = InetAddress.getByName(InetAddress.getLocalHost().getHostAddress());
|
||||||
|
} catch (IOException ex) {
|
||||||
|
System.out.println("There is no socket connection. Sorry.");
|
||||||
|
System.out.println(ex.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem por meio de uma conexão TCP pública com o peer de destino.
|
||||||
|
*
|
||||||
|
* <p>A conexão pública existente para o endereço informado é reutilizada.
|
||||||
|
* Caso não exista uma conexão válida, uma nova conexão é estabelecida antes
|
||||||
|
* do envio. Falhas durante o estabelecimento ou envio são registradas na
|
||||||
|
* saída padrão e não são propagadas ao chamador.</p>
|
||||||
|
*
|
||||||
|
* @param msg mensagem que será enviada.
|
||||||
|
* @param destinationAddress endereço IP do peer que receberá a mensagem.
|
||||||
|
*/
|
||||||
|
public void send(Message msg, InetAddress destinationAddress) {
|
||||||
|
try {
|
||||||
|
TcpConnection connection = getPublicConnection(destinationAddress, main.getIdentifier(), main.getIdentifier());
|
||||||
|
if (connection == null) {
|
||||||
|
System.out.println("Could not establish TCP connection.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
connection.send(msg.toByteArray());
|
||||||
|
} catch (Exception ex) {
|
||||||
|
System.out.println("Could not send TCP message.");
|
||||||
|
System.out.println(ex.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 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.
|
||||||
|
* @param senderId identificador do remetente da conexão.
|
||||||
|
* @param receiverId identificador do plugin que receberá os dados.
|
||||||
|
* @return a conexão privada estabelecida ou {@code null} quando a criação
|
||||||
|
* da conexão falhar.
|
||||||
|
* @throws IllegalArgumentException se o endereço de destino for o endereço
|
||||||
|
* local desta instância.
|
||||||
|
*/
|
||||||
|
public TcpConnection createPrivateConnection(InetAddress destinationAddress, String senderId, String receiverId) {
|
||||||
|
return establishOutgoingConnection(destinationAddress, senderId, receiverId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 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 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>
|
||||||
|
*
|
||||||
|
* @param destinationAddress endereço IP do peer de destino.
|
||||||
|
* @param senderId identificador usado como remetente no estabelecimento da conexão.
|
||||||
|
* @param receiverId identificador usado como destinatário no estabelecimento da conexão.
|
||||||
|
* @return uma conexão pública válida ou {@code null} caso não seja possível
|
||||||
|
* estabelecê-la.
|
||||||
|
*/
|
||||||
|
private synchronized TcpConnection getPublicConnection(InetAddress destinationAddress, String senderId, String receiverId) {
|
||||||
|
TcpConnection connection;
|
||||||
|
|
||||||
|
connection = connectionManager.getPublicConnection(destinationAddress);
|
||||||
|
if (connection != null && !connection.isClosed()) return connection;
|
||||||
|
|
||||||
|
connection = establishOutgoingConnection(destinationAddress, senderId, receiverId, false);
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aguarda e aceita novas conexões TCP.
|
||||||
|
*
|
||||||
|
* <p>Cada socket aceito é encaminhado para processamento assíncrono,
|
||||||
|
* interpretado como uma {@link TcpConnection}, registrado pelo
|
||||||
|
* {@link ConnectionManager} e associado ao receptor adequado.</p>
|
||||||
|
*/
|
||||||
|
private void receive() {
|
||||||
|
while (running) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
Socket socket = serverSocket.accept();
|
||||||
|
acceptIncomingConnection(socket);
|
||||||
|
|
||||||
|
} catch (IOException ex) {
|
||||||
|
if (!running) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("Error accepting TCP connection.");
|
||||||
|
System.out.println(ex.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Estabelece uma conexão TCP de saída com outro peer.
|
||||||
|
*
|
||||||
|
* <p>O método impede conexões com o próprio endereço local, cria a conexão
|
||||||
|
* por meio da {@link ConnectionFactory}, registra-a no gerenciador de
|
||||||
|
* conexões e inicia uma tarefa para receber dados continuamente.</p>
|
||||||
|
*
|
||||||
|
* @param destinationAddress endereço IP do peer de destino.
|
||||||
|
* @param sender identificador do remetente.
|
||||||
|
* @param receiver identificador do destinatário.
|
||||||
|
* @param isPrivate {@code true} para uma conexão destinada a um plugin
|
||||||
|
* específico; {@code false} para uma conexão pública.
|
||||||
|
* @return a conexão estabelecida ou {@code null} se a
|
||||||
|
* {@link ConnectionFactory} não conseguir criá-la.
|
||||||
|
* @throws IllegalArgumentException se o destino for o endereço desta máquina.
|
||||||
|
*/
|
||||||
|
private TcpConnection establishOutgoingConnection(InetAddress destinationAddress, String sender, String receiver, boolean isPrivate) {
|
||||||
|
if (address.equals(destinationAddress)) {
|
||||||
|
System.out.println("Failed to get socket.");
|
||||||
|
throw new IllegalArgumentException("Connections to the local host are forbidden.");
|
||||||
|
}
|
||||||
|
|
||||||
|
TcpConnection connection = ConnectionFactory.createConnection(destinationAddress, main.getPort(), sender, receiver, isPrivate);
|
||||||
|
if (connection == null) return null;
|
||||||
|
|
||||||
|
saveConnection(connection);
|
||||||
|
|
||||||
|
connectionExecutor.submit(() -> {
|
||||||
|
startReceiver(connection);
|
||||||
|
});
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Agenda o processamento de uma conexão TCP recebida.
|
||||||
|
*
|
||||||
|
* <p>A conexão é interpretada pela {@link ConnectionFactory}, registrada
|
||||||
|
* no gerenciador e associada a uma tarefa de recepção. O processamento é
|
||||||
|
* executado de forma assíncrona pelo executor compartilhado.</p>
|
||||||
|
*
|
||||||
|
* @param socket socket aceito pelo {@link ServerSocket}.
|
||||||
|
*/
|
||||||
|
private void acceptIncomingConnection(Socket socket) {
|
||||||
|
connectionExecutor.submit(() -> {
|
||||||
|
TcpConnection connection = ConnectionFactory.receiveConnection(socket);
|
||||||
|
if (connection == null) return;
|
||||||
|
|
||||||
|
saveConnection(connection);
|
||||||
|
startReceiver(connection);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registra uma conexão no gerenciador de acordo com seu tipo.
|
||||||
|
*
|
||||||
|
* <p>Conexões privadas são armazenadas na coleção de conexões privadas;
|
||||||
|
* as demais são armazenadas na coleção de conexões públicas.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão que será registrada.
|
||||||
|
*/
|
||||||
|
private void saveConnection(TcpConnection connection) {
|
||||||
|
if (connection.isPrivate()) {
|
||||||
|
connectionManager.addPrivateConnection(connection);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
connectionManager.addPublicConnection(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seleciona e inicia o receptor adequado para uma conexão.
|
||||||
|
*
|
||||||
|
* <p>Conexões públicas são tratadas pelo receptor de mensagens públicas.
|
||||||
|
* Conexões privadas destinadas ao próprio sistema são tratadas
|
||||||
|
* separadamente; as demais são encaminhadas ao plugin identificado como
|
||||||
|
* destinatário. Quando solicitado, o plugin também é notificado sobre o
|
||||||
|
* estabelecimento da conexão.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão cujo fluxo de entrada será processado.
|
||||||
|
*/
|
||||||
|
private void startReceiver(TcpConnection connection) {
|
||||||
|
|
||||||
|
if (!connection.isPrivate()) {
|
||||||
|
publicConnectionReceiver(connection);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connection.getReceiver().equals(main.getIdentifier())) {
|
||||||
|
systemConnectionReceiver(connection);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa continuamente as mensagens recebidas em uma conexão pública.
|
||||||
|
*
|
||||||
|
* <p>As mensagens são desserializadas e, quando são instâncias de
|
||||||
|
* {@link Message}, encaminhadas a todos os plugins da aplicação. Mensagens
|
||||||
|
* de controle do sistema podem encerrar a conexão ou registrar uma
|
||||||
|
* condição de erro.</p>
|
||||||
|
*
|
||||||
|
* <p>O método também trata timeouts e erros de I/O, removendo a conexão
|
||||||
|
* do {@link ConnectionManager} quando ela deixa de ser utilizável.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão pública da qual as mensagens serão recebidas.
|
||||||
|
*/
|
||||||
|
private void publicConnectionReceiver(TcpConnection connection) {
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
byte[] bytes = connection.receive();
|
||||||
|
|
||||||
|
SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(bytes);
|
||||||
|
|
||||||
|
if (sysMessage == null) {
|
||||||
|
for (Plugin plugin : main.getPlugins()) {
|
||||||
|
plugin.receiveMessage(bytes);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
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()) {
|
||||||
|
connectionManager.closeConnection(connection, "Connection timeout");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
connectionManager.closeConnection(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa os dados recebidos em uma conexão privada e os encaminha
|
||||||
|
* ao plugin destinatário.
|
||||||
|
*
|
||||||
|
* <p>Dados que não representam mensagens de controle são entregues
|
||||||
|
* diretamente ao {@link PrivateConnectionPlugin}. Mensagens de controle
|
||||||
|
* relacionadas ao encerramento ou a erros internos provocam a notificação
|
||||||
|
* 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, Plugin plugin) {
|
||||||
|
if (plugin instanceof PrivateConnectionPlugin privatePlugin) {
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
byte[] message = connection.receive();
|
||||||
|
SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(message);
|
||||||
|
|
||||||
|
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()) {
|
||||||
|
connectionManager.closeConnection(connection, "Connection timeout");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
connectionManager.closeConnection(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa mensagens recebidas em uma conexão destinada ao próprio sistema.
|
||||||
|
*
|
||||||
|
* <p>Atualmente, mensagens destinadas ao sistema são apenas verificadas
|
||||||
|
* quanto ao seu formato de controle. Não há processamento adicional de
|
||||||
|
* mensagens de sistema neste método.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão destinada ao identificador da própria aplicação.
|
||||||
|
*/
|
||||||
|
private void systemConnectionReceiver(TcpConnection connection) {
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
byte[] message = connection.receive();
|
||||||
|
try (ByteArrayInputStream bis = new ByteArrayInputStream(message);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
||||||
|
|
||||||
|
SysInfoMessage sysMessage = SysInfoMessage.parseSystemInfo(message);
|
||||||
|
if (sysMessage != null) continue;
|
||||||
|
|
||||||
|
//TODO: Ainda não existem mensagens trocadas entre o sistema.
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (SocketTimeoutException ex) {
|
||||||
|
if (connection.hasTimedOut()) return;
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
connectionManager.closeConnection(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 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) {
|
||||||
|
connectionManager.closeConnection(
|
||||||
|
connection,
|
||||||
|
Objects.requireNonNullElse(description, "No reason provided")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
receive();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encerra o servidor TCP e libera os recursos associados.
|
||||||
|
*
|
||||||
|
* <p>Interrompe o laço de aceitação de conexões, fecha o
|
||||||
|
* {@link ServerSocket}, encerra todas as conexões gerenciadas e interrompe
|
||||||
|
* as tarefas do executor.</p>
|
||||||
|
*
|
||||||
|
* <p>Após a chamada, esta instância não deve ser reutilizada para aceitar
|
||||||
|
* novas conexões.</p>
|
||||||
|
*/
|
||||||
|
public void close() {
|
||||||
|
running = false;
|
||||||
|
|
||||||
|
if (serverSocket != null) {
|
||||||
|
try {
|
||||||
|
serverSocket.close();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
logger.log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connectionManager.closeAllConnections("The peer must have closed the application or changed ports");
|
||||||
|
|
||||||
|
connectionExecutor.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.net.Message;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class SysInfoMessage extends Message {
|
||||||
|
|
||||||
|
private final SysInfoType type;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
public SysInfoMessage(String message, SysInfoType type) {
|
||||||
|
this.message = message;
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SysInfoType getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void sendSystemInfo(TcpConnection connection, SysInfoType type, String description) {
|
||||||
|
try {
|
||||||
|
SysInfoMessage error = new SysInfoMessage(description, type);
|
||||||
|
connection.send(error.toByteArray());
|
||||||
|
} catch (IOException ex) {
|
||||||
|
Logger.getLogger(SysInfoMessage.class.getName()).log(Level.WARNING, null, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static SysInfoMessage parseSystemInfo(byte[] bytes) {
|
||||||
|
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
||||||
|
|
||||||
|
Object object = ois.readObject();
|
||||||
|
if (object instanceof SysInfoMessage) {
|
||||||
|
return (SysInfoMessage) object;
|
||||||
|
}
|
||||||
|
} catch (IOException | ClassNotFoundException ex) {
|
||||||
|
Logger.getLogger(SysInfoMessage.class.getName()).log(Level.WARNING, null, ex);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
public enum SysInfoType {
|
||||||
|
CONNECTION_REJECTED,
|
||||||
|
RECEIVER_NOT_FOUND,
|
||||||
|
MESSAGE_REJECTED,
|
||||||
|
INTERNAL_ERROR,
|
||||||
|
CONNECTION_CLOSED,
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import java.io.DataInputStream;
|
||||||
|
import java.io.DataOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.net.SocketException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Representa uma conexão TCP ativa com um peer remoto.
|
||||||
|
*
|
||||||
|
* <p>A conexão permite o envio e recebimento de mensagens, além de manter
|
||||||
|
* informações sobre o endereço remoto e metadados da conexão, como remetente,
|
||||||
|
* destinatário e se a conexão é privada.</p>
|
||||||
|
*
|
||||||
|
* @author Gustavo
|
||||||
|
*/
|
||||||
|
public class TcpConnection {
|
||||||
|
|
||||||
|
private final Socket socket;
|
||||||
|
private final DataInputStream input;
|
||||||
|
private final DataOutputStream output;
|
||||||
|
private final InetAddress address;
|
||||||
|
private String sender;
|
||||||
|
private String receiver;
|
||||||
|
private boolean isPrivate;
|
||||||
|
private volatile long lastActivity;
|
||||||
|
private long timeout;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria uma conexão TCP a partir de um socket existente.
|
||||||
|
*
|
||||||
|
* @param socket socket utilizado para a comunicação
|
||||||
|
* @throws IOException se não for possível obter os fluxos de entrada ou saída
|
||||||
|
* do socket
|
||||||
|
*/
|
||||||
|
TcpConnection(Socket socket) throws IOException {
|
||||||
|
this.socket = socket;
|
||||||
|
this.input = new DataInputStream(socket.getInputStream());
|
||||||
|
this.output = new DataOutputStream(socket.getOutputStream());
|
||||||
|
this.address = socket.getInetAddress();
|
||||||
|
this.lastActivity = System.currentTimeMillis();
|
||||||
|
this.timeout = 300_000; // 5 minutos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem pela conexão.
|
||||||
|
*
|
||||||
|
* <p>A mensagem é enviada precedida pelo seu tamanho, permitindo que o
|
||||||
|
* receptor determine quantos bytes devem ser lidos.</p>
|
||||||
|
*
|
||||||
|
* @param message mensagem a ser enviada
|
||||||
|
* @throws IOException se ocorrer um erro durante o envio
|
||||||
|
*/
|
||||||
|
public synchronized void send(byte[] message) throws IOException {
|
||||||
|
output.writeInt(message.length);
|
||||||
|
output.write(message);
|
||||||
|
output.flush();
|
||||||
|
updateLastActivity();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recebe uma mensagem da conexão.
|
||||||
|
*
|
||||||
|
* <p>Primeiro lê o tamanho da mensagem e, em seguida, lê aquantidade
|
||||||
|
* correspondente de bytes.</p>
|
||||||
|
*
|
||||||
|
* @return mensagem recebida
|
||||||
|
* @throws IOException se o tamanho da mensagem for inválido ou se a conexão
|
||||||
|
* for encerrada antes que a mensagem seja completamente recebida
|
||||||
|
*/
|
||||||
|
byte[] receive() throws IOException {
|
||||||
|
int length = input.readInt();
|
||||||
|
|
||||||
|
if (length < 0) throw new IOException("Invalid message length.");
|
||||||
|
|
||||||
|
byte[] message = input.readNBytes(length);
|
||||||
|
|
||||||
|
if (message.length != length) {
|
||||||
|
throw new IOException("Connection closed before receiving the complete message.");
|
||||||
|
}
|
||||||
|
|
||||||
|
updateLastActivity();
|
||||||
|
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica se o socket da conexão está fechado.
|
||||||
|
*
|
||||||
|
* @return {@code true} se o socket estiver fechado;
|
||||||
|
* {@code false} caso contrário
|
||||||
|
*/
|
||||||
|
public boolean isClosed() {
|
||||||
|
return socket.isClosed();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha o socket da conexão.
|
||||||
|
*
|
||||||
|
* @throws IOException se ocorrer um erro ao fechar o socket
|
||||||
|
*/
|
||||||
|
void close() throws IOException {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retorna o endereço do peer remoto conectado.
|
||||||
|
*
|
||||||
|
* @return endereço IP do peer remoto
|
||||||
|
*/
|
||||||
|
public InetAddress getAddress() {
|
||||||
|
return address;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atualiza o instante da última atividade da conexão.
|
||||||
|
*/
|
||||||
|
private void updateLastActivity() {
|
||||||
|
lastActivity = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Define o tempo limite de leitura do socket.
|
||||||
|
*
|
||||||
|
* @param timeout tempo limite, em milissegundos
|
||||||
|
* @throws SocketException se ocorrer um erro ao definir o tempo limite
|
||||||
|
*/
|
||||||
|
void setTimeout(int timeout) throws SocketException {
|
||||||
|
socket.setSoTimeout(timeout);
|
||||||
|
this.timeout = timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica se a conexão ficou inativa pelo tempo limite configurado.
|
||||||
|
*
|
||||||
|
* <p>A verificação é baseada no instante da última atividade registrada
|
||||||
|
* durante o envio ou recebimento de uma mensagem.</p>
|
||||||
|
*
|
||||||
|
* @return {@code true} se a conexão estiver inativa há pelo menos 5 minutos;
|
||||||
|
* {@code false} caso contrário
|
||||||
|
*/
|
||||||
|
boolean hasTimedOut() {
|
||||||
|
return System.currentTimeMillis() - lastActivity >= timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getReceiver() {
|
||||||
|
return receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSender() {
|
||||||
|
return sender;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPrivate() {
|
||||||
|
return isPrivate;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setSender(String sender) {
|
||||||
|
this.sender = sender;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setReceiver(String receiver) {
|
||||||
|
this.receiver = receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setPrivate(boolean aPrivate) {
|
||||||
|
isPrivate = aPrivate;
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
-6
@@ -3,7 +3,7 @@
|
|||||||
* To change this template file, choose Tools | Templates
|
* To change this template file, choose Tools | Templates
|
||||||
* and open the template in the editor.
|
* and open the template in the editor.
|
||||||
*/
|
*/
|
||||||
package pitiupi.net;
|
package pitiupi.net.udp;
|
||||||
|
|
||||||
import pitiupi.GUI.MainWindow;
|
import pitiupi.GUI.MainWindow;
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
@@ -13,6 +13,9 @@ import java.io.ObjectInputStream;
|
|||||||
import java.net.*;
|
import java.net.*;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import pitiupi.net.HeartbeatMessage;
|
||||||
|
import pitiupi.net.Message;
|
||||||
import pitiupi.plugin.Plugin;
|
import pitiupi.plugin.Plugin;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -71,8 +74,8 @@ public class SocketUDP extends Thread {
|
|||||||
* @param msg mensagem serializada a ser enviada.
|
* @param msg mensagem serializada a ser enviada.
|
||||||
* @throws IOException caso ocorra um erro durante o envio.
|
* @throws IOException caso ocorra um erro durante o envio.
|
||||||
*/
|
*/
|
||||||
public void sendMulticast(byte[] msg) throws IOException {
|
public void sendMulticast(Message msg) throws IOException {
|
||||||
send(msg, this.address);
|
send(msg, address);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,7 +85,7 @@ public class SocketUDP extends Thread {
|
|||||||
* @param destinationAddress endereço IP do peer destinatário.
|
* @param destinationAddress endereço IP do peer destinatário.
|
||||||
* @throws IOException caso ocorra um erro durante o envio.
|
* @throws IOException caso ocorra um erro durante o envio.
|
||||||
*/
|
*/
|
||||||
public void sendUnicast(byte[] msg, InetAddress destinationAddress) throws IOException {
|
public void sendUnicast(Message msg, InetAddress destinationAddress) throws IOException {
|
||||||
send(msg, destinationAddress);
|
send(msg, destinationAddress);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,9 +96,10 @@ public class SocketUDP extends Thread {
|
|||||||
* @param destinationAddress endereço de destino.
|
* @param destinationAddress endereço de destino.
|
||||||
* @throws IOException caso ocorra um erro durante o envio.
|
* @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;
|
DatagramPacket msgPacket;
|
||||||
msgPacket = new DatagramPacket(msg, msg.length, destinationAddress, this.main.getPort());
|
byte[] buf = msg.toByteArray();
|
||||||
|
msgPacket = new DatagramPacket(buf, buf.length, destinationAddress, this.main.getPort());
|
||||||
multicastSocket.send(msgPacket);
|
multicastSocket.send(msgPacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,11 +144,13 @@ 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) {
|
||||||
main.getHeartbeatManager().receiveHeartbeat(heartbeat, msgPacket.getAddress());
|
main.getHeartbeatManager().receiveHeartbeat(heartbeat, msgPacket.getAddress());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Plugin plugin : main.getPlugins()) {
|
for (Plugin plugin : main.getPlugins()) {
|
||||||
System.out.println(msgPacket.getAddress().toString());
|
System.out.println(msgPacket.getAddress().toString());
|
||||||
plugin.receiveMessage(msgPacket.getData());
|
plugin.receiveMessage(msgPacket.getData());
|
||||||
@@ -4,9 +4,9 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.plugin;
|
package pitiupi.plugin;
|
||||||
|
|
||||||
import javax.swing.JMenu;
|
|
||||||
import pitiupi.GUI.MainWindow;
|
import pitiupi.GUI.MainWindow;
|
||||||
import pitiupi.net.Message;
|
import pitiupi.net.Message;
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interface base para plugins da aplicação.
|
* Interface base para plugins da aplicação.
|
||||||
@@ -21,6 +21,7 @@ public interface Plugin {
|
|||||||
public String getName();
|
public String getName();
|
||||||
public String getAuthor();
|
public String getAuthor();
|
||||||
public String getVersion();
|
public String getVersion();
|
||||||
|
public String getIdentifier();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inicializa o plugin.
|
* Inicializa o plugin.
|
||||||
@@ -47,4 +48,5 @@ public interface Plugin {
|
|||||||
* @param message mensagem serializada recebida.
|
* @param message mensagem serializada recebida.
|
||||||
*/
|
*/
|
||||||
public void receiveMessage(byte[] message);
|
public void receiveMessage(byte[] message);
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package pitiupi.plugin;
|
||||||
|
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
|
||||||
|
public interface PrivateConnectionPlugin extends Plugin {
|
||||||
|
public void receivePrivateConnection(TcpConnection connection);
|
||||||
|
public void receiveBytes(TcpConnection connection, byte[] bytes);
|
||||||
|
public void onSocketClosed(TcpConnection connection);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user