import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement() public class Message { private String text; private String date; // il costruttore vuoto serve per il marshal e l'unmarshal public Message() { } public Message(String text, String date) { this.text = text; this.date = date; } @XmlElement() public String getText() { return text; } public void setText(String text) { this.text = text; } @XmlElement() public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringReader; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; public class MessageThread extends Thread { private Socket socket; private Socket alarmsocket; private BufferedReader socketBuffer; private PrintWriter socketWriter; private PrintWriter alarmsocketWriter; public MessageThread(Socket socket) { this.socket = socket; try { alarmsocket = new Socket("192.168.10.2", 5000); } catch (IOException ex) { Logger.getLogger(MessageThread.class.getName()).log(Level.SEVERE, null, ex); } } public MessageThread(Socket socket, String ip, int port) { this.socket = socket; try { alarmsocket = new Socket(ip, port); } catch (IOException ex) { Logger.getLogger(MessageThread.class.getName()).log(Level.SEVERE, null, ex); } } public void Run() { boolean enable = true; try { // definizione oggetti per comunicazione via socket socketBuffer = new BufferedReader(new InputStreamReader(socket.getInputStream())); socketWriter = new PrintWriter(socket.getOutputStream()); alarmsocketWriter = new PrintWriter(alarmsocket.getOutputStream()); // definizione per unmarshal JAXBContext jaxbContext = JAXBContext.newInstance(Message.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); // ciclo di lettura dal socket while(enable) { String str = socketBuffer.readLine(); // conversione della stringa arrivata nell'oggetto corrispondente Message msg = (Message) unmarshaller.unmarshal(new StringReader(str)); String text = msg.getText(); if (text.indexOf("Allarme:") >= 0) { socketWriter.println("ALM"); alarmsocketWriter.println("A"); } else if (text.indexOf("Messaggio:") >= 0) { socketWriter.println("MSG"); } else if (text.equals("end connection")) { enable = false; } else { socketWriter.println("NOT"); } } } catch (Exception ex) { Logger.getLogger(MessageThread.class.getName()).log(Level.SEVERE, null, ex); } } }