serializzazione e deserializzazione messaggio nella classe messaggio

This commit is contained in:
2023-05-05 13:47:25 +02:00
parent fdadd62321
commit bbc6a563c7
13 changed files with 25 additions and 7 deletions
+2 -2
View File
@@ -1,4 +1,4 @@
#Fri, 05 May 2023 12:43:45 +0200
#Fri, 05 May 2023 13:44:03 +0200
/home/docente/Scaricati/chifu=
/home/docente/Progetti/Didattica_Socket/chifu=
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
+3 -1
View File
@@ -80,7 +80,9 @@ public class Finestra extends javax.swing.JFrame {
}//GEN-LAST:event_jButton1ActionPerformed
private void avviaLoop() {
new Thread(() -> {
while(true) {
if(!server_on) {
System.out.println("Avvio il server");
@@ -89,10 +91,10 @@ public class Finestra extends javax.swing.JFrame {
try
{
GestoreServer.messaggio = GestoreServer.ascolta();
server_on = false;
System.out.println("ho ricevuto un qualcosa e dovrei avere un messaggio");
jTextArea1.append(GestoreServer.messaggio.messaggio + "\n");
GestoreServer.messaggio = null;
server_on = false;
repaint();
System.out.println("fine metodo");
} catch (Exception ex) {
+4 -4
View File
@@ -27,7 +27,7 @@ public class GestoreServer {
System.out.println("Ho ricevuto un messaggio da: " +
pacchetto.getAddress().getHostAddress());
messaggio = (Messaggio) new ObjectInputStream(new ByteArrayInputStream(pacchetto.getData())).readObject();
messaggio = Messaggio.toMessaggio(pacchetto.getData());
server.close();
System.out.println("Server chiuso");
@@ -42,13 +42,13 @@ public class GestoreServer {
InetAddress destinatario = InetAddress.getByName(host);
DatagramSocket client = new DatagramSocket();
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(messaggio);
byte[] flusso_messaggio = out.toByteArray();
byte[] flusso_messaggio = messaggio.toByteArray();
DatagramPacket pacchetto = new DatagramPacket(flusso_messaggio,
flusso_messaggio.length, destinatario, port);
client.send(pacchetto);
client.close();
}
}
+16
View File
@@ -1,5 +1,10 @@
package chifu;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Messaggio implements Serializable {
@@ -12,4 +17,15 @@ public class Messaggio implements Serializable {
this.nome = ip;
this.messaggio = messaggio;
}
public byte[] toByteArray() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(this);
return out.toByteArray();
}
public static Messaggio toMessaggio(byte[] vettore) throws IOException, ClassNotFoundException {
Messaggio messaggio = (Messaggio) new ObjectInputStream(new ByteArrayInputStream(vettore)).readObject();
return messaggio;
}
}