JAVA - Serializacja obiektów, interfejs Serializable. class Box implements Serializable { private int i ; Box(int x ) { i =x; } int showInBox() { return i;} } class NamedBox implements Serializable { Box a; NamedBox(int x) { a = new Box(x); } int showNamedBox() { return - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
class Test implements Serializable { private transient int i ; // stos. dla Serializable private String s; Test(int x, String t ) { i =x; s = t; } String showS() { return s;} int showI() { return i ;}}
4
JAVA - serializacja i deserializacja sieci obiektów do pojedynczego strumienia
import java.io.*; import java.util.*;
public class Prog91{
public static void main(String [] arg) throws IOException, ClassNotFoundException {
Group l1 = new Group(1);
Group l2 = new Group(2);
Student s1 = new Student("Marek",l1);
Student s2 = new Student("Pawel",l1);
Student s3 = new Student("Olek ",l2);
s1.whereIs(); s2.whereIs(); s3.whereIs();
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteout);
System.out.println(" po odczycie ze strumienia : " );
ByteArrayInputStream byteinp = new ByteArrayInputStream(byteout.toByteArray());
ObjectInputStream inp = new ObjectInputStream(byteinp);
Student s4 = (Student)inp.readObject(); // grupa l1
Student s5 = (Student)inp.readObject(); // grupa l1
Student s6 = (Student)inp.readObject();
s4.whereIs(); s5.whereIs(); s6.whereIs();
inp.close(); }} //Prog91
class Group implements Serializable { int nr; Group(int n ) { nr = n;} String gAddres() { return super.toString();} int inGroup() {return nr;}}class Student implements Serializable { String s; Group g ; Student(String t, Group x ) { s = t; g = x;} void whereIs() {System.out.println(s + " is in group nr " + g.inGroup() +" ” g.gAddres());}}
Obiekt Group który zawierają s4 i s5 jest tworzony tylko raz
5
JAVA - serializacja i deserializacja sieci obiektów - do wielu strumieni (1)
public class Prog92{
public static void main(String [] arg) throws IOException, ClassNotFoundException {
for(int i = 0; i < student2.size(); ((Student)student2.get(i++)).whereIs());
inp2.close();
}
} //Prog92
Deserializując obiekty z różnych strumieni system nie jest w stanie stwierdzić identyczności tych obiektów
7
JAVA - serializacja i deserializacja sieci obiektów - do wielu strumieni (3)
class Group implements Serializable {
int nr;
Group(int n ) { nr = n;}
String gAddres() { return super.toString();}
int inGroup() {return nr;}
}
class Student implements Serializable { String s; Group g ; Student(String t, Group x ) { s = t; g = x;} String sAddres() { return super.toString();} void whereIs() {System.out.println(s + " adress = " + sAddres() + " is in group nr " + g.inGroup() +" " + g.gAddres() );}}
W konsekwencji tworzonych jest dwa razy więcej obiektów
8
JAVA - Aplety
Generalne zasady, aplet nie może:
- odczytywać ani zapisywać plików na komputerze użytkownika,
- komunikować się z inną witryną WWW niż ta, z której został załadowany,
- uruchamiać żadnych programów na komputerze użytkownika,
- ładować ani pobierać z komputera użytkownika żadnych programów.
Aplety powinny być pakowane w pliki JAR .
Aplet:
działa jako część przeglądarki sieciowej i potrafi reagować na takie zdarzenia jak przeładowanie
strony WWW w jej oknie,
obsługuje graficzny interfejs użytkownika
W tej części wykładu:
-tworzenie i uruchamianie apletów,
-przykładowe komponenty i obsługa zdarzeń
-grafika i dźwięki w apletach,
-tworzenie łącz w apletach
9
JAVA – Aplety, główne metody
import java.awt.*; //Font, Color, Graphics2D
class Licz { int licz_Init; int licz_Start; int licz_Stop; int licz_Destroy; }
// wszystkie applety musza być public bo JApplet jest public
public class A1 extends javax.swing.JApplet {
private Licz licznik = new Licz();
public void init() { // inicjalizacja appletu
setBackground(Color.white); // zmiana kolory tła kontenera (tutaj appletu)
licznik.licz_Init++;}
public void start() { //uruchamianie appletu,
licznik.licz_Start++;} //przy ponownym ładowaniu strony
class ConButton extends Button { static int licznik = 0; public int nr ; ConButton(String n) { super(n); nr = licznik++;} } public class Pn4 implements ActionListener {
static ConButton b1 = new ConButton("Action READ I ");static ConButton b2 = new ConButton("Action READ II");static JTextArea tx = new JTextArea(10,10);static JLabel et = new JLabel("File to read I / II ?");static JTextField n = new JTextField(15);static JScrollPane js = new JScrollPane(tx);static JFrame ramka = new JFrame("Obsluga strumieni");
public void actionPerformed(ActionEvent e){ if (e.getSource() instanceof ConButton) { if ( ((ConButton)e.getSource()).nr == 0 ) { try { String line = new String(); URL adres = new URL(n.getText());
try{ BufferedReader czytaj = new BufferedReader(new InputStreamReader(adres.openStream())); while ((line = czytaj.readLine())!=null) tx.append(line+'\n'); //dopisuje } catch (IOException E) {JOptionPane.showMessageDialog(null,"Error in FILE connection"); } } catch (MalformedURLException ex) { JOptionPane.showMessageDialog(null,"Error URL"); } }else { try { String line = new String(); URL adres = new URL(n.getText()); URLConnection polaczenie = adres.openConnection(); polaczenie.connect(); try{ BufferedReader czytaj = new BufferedReader(new InputStreamReader(polaczenie.getInputStream())); while ((line = czytaj.readLine())!=null) tx.append(line+'\n'); //dopisuje } catch (IOException E) { JOptionPane.showMessageDialog(null,"Error in FILE connection"); } } catch (MalformedURLException ex) {JOptionPane.showMessageDialog(null,"Error URL"); } catch (IOException E) { JOptionPane.showMessageDialog(null,"Error in URLconnection"); } } // dodatkowo IOException dla URLConnection }}}
36
JAVA – Aplety i połączenia poprzez adresy URL
public class A19 extends javax.swing.JApplet {
private static JFrame ramka = new JFrame("Autoryzacja dostepu");
private static JButton ident = new JButton("Wywolaj identyfikacje");
private static JTextField haslo = new JTextField(20);
private static String wzor = new String("JAVA");
private static URL adres;
private static JTextArea obszarTekstu = new JTextArea(20,20);
Socket gniazdo = new Socket(nazwa hosta , nr portu );
gniazdo.getInputStream()
gniazdo.getOutputStream()
Gniazdo.close()
Porty 1 – 1024 zarezerwowane są na usługi systemowe !!
(Assigned Numbers Authority)
Można używać dla swoich celów portów o numerach większych niż 1024 i mniejszych od 65535.
Niektóre wyższe numery portów są wykorzystywane->
www.sockets.com/services.htm
39
JAVA –gniazda
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton)
{
String line = new String();
String host = new String();
String user = new String();
StringTokenizer data = new StringTokenizer(n.getText(),"@");
Integer port = new Integer(79); //port zarezerwowany dla uslufi FINGER
user = data.nextToken();
host = data.nextToken();
try{
Socket gniazdo = new Socket(host,port.intValue());
PrintStream wyslij = new PrintStream(gniazdo.getOutputStream());
wyslij.print(user+"\015\012"); //protokół FINGER wymaga znaków karetki i wysunięcia na końcu!
BufferedReader odbierz = new BufferedReader(new InputStreamReader(gniazdo.getInputStream()));
while ((line = odbierz.readLine())!=null) System.out.println(line);
gniazdo.close();
}
catch (IOException E) {JOptionPane.showMessageDialog(null,"Error in FILE connection"); }
}}}
40
JAVA – gniazda, serwery
public class Pn6 { public static int port = 1995;public static void main(String [] arg) { try { ServerSocket gniazdoS = new ServerSocket(port); System.out.println(" Serwer " + gniazdoS + "już pracuje..."); //informacje gniazda serwera i nr portu try { Socket gniazdo = gniazdoS.accept(); //blokowanie pracy aż do nadejścia połączenia try { System.out.println(" Połączenie nastąpiło z klientem " + gniazdo); //adres IP klienta i nr portu BufferedReader czytaj = new BufferedReader(new InputStreamReader(gniazdo.getInputStream())); PrintWriter pisz = new PrintWriter(new BufferedWriter(new OutputStreamWriter(gniazdo.getOutputStream())),true); // true jako 2 parametr określa automatyczne opróżnianie bufora po każdym println String line = new String(); while(true) { line = czytaj.readLine(); pisz.println(line); System.out.println(line); // odsyła ten sam tekst aż do wystąpienia "logout" if (line.equals("logout")) break; } } catch (IOException e) {System.err.println("wystapil blad klasy IO");} } catch (IOException e) {System.err.println("wystapil blad klasy IO");} finally { gniazdoS.close(); System.out.println("koniec pracy");} } catch (IOException e) {System.err.println("Nie można ustanowić serwera");}}}
41
JAVA – gniazda, klienci
public class Pn7 { public static int port = 1995;public static void main(String [] arg) {try { InetAddress adres = InetAddress.getByName(null); // uzyskujemy adres lokalny Socket gniazdo = new Socket(adres,port);
System.out.println(" Serwer " + gniazdo + "juz pracuje..."); try { System.out.println(" jest gniazdo " + gniazdo); BufferedReader czytaj = new BufferedReader(new InputStreamReader(gniazdo.getInputStream())); PrintWriter pisz = new PrintWriter(new BufferedWriter(new OutputStreamWriter(gniazdo.getOutputStream())),true); String line = new String(); BufferedReader wejscie = new BufferedReader(new InputStreamReader(System.in));
while(true) { line = wejscie.readLine(); // co przeczyta z klawiatury to wysyła do serwera pisz.println(line); line = czytaj.readLine(); System.out.println("server :" + line); //odpowiedzi serwera na konsole if (line.equals("logout")) break; } } catch (IOException e) {System.err.println("wystąpił błąd klasy IO");} finally { gniazdo.close(); System.out.println("koniec pracy");} } catch (IOException e) {System.err.println("Nie można ustanowić serwera");}}}