serializzazione e deserializzazione messaggio nella classe messaggio
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user