Skocz do zawartości
soska66

Problem W Aplikacji "serwer-klient" W Java

Rekomendowane odpowiedzi

Nowy problem. tym razem w pliku servera. program ma wysylac wiadomosc z klienta do serwera i spowrotem. to pierwsze juz dziala. teraz bawie sie kierunkiem serwer-klient

 

public class Server implements ActionListener,Runnable {	ServerSocket serversocket;	public Server(int port){  try{ 	 serversocket=new ServerSocket(port,64000);    }catch(Exception e){System.out.println("Server socket not created...");}  new Thread(this).start();	}		public void run(){  while(true){ 	 System.out.println("Waiting for incoming connection..\n"); 	 try{    Socket socket=serversocket.accept();    new SingleThread(socket); 	 }catch(Exception e){System.out.println("An error occured...\n");}  }	}	public static void main(String args[]){  Frame f=new Frame();  TextField t=new TextField();  f.setBounds(0,0,400,200);  f.setLayout(new GridBagLayout());    t=new TextField("Tu wpisz tresc wiadomosci...");  t.setColumns(40);        f.add(t);    Button button=new Button("Send"); 	   button.addActionListener(this);  f.add(button);  f.show();    int port=0;  if(args.length>0){ 	 try{    port=new Integer(args[0]).intValue(); 	 }catch(Exception e){port=7000;}    new Server(port);  }else{ 	 System.out.println("Usage: java Server por \nExample: java Server 7001\n");  }	}	public void actionPerformed(ActionEvent evt) {    Button b= (Button)evt.getSource();           	 	}}class SingleThread implements Runnable{	DataInputStream in;	DataOutputStream out;	public SingleThread(Socket socket){  try{ 	 in=new DataInputStream(socket.getInputStream()); 	 out=new DataOutputStream(socket.getOutputStream());  }catch(Exception e){System.out.println("Streams not initialized...");}    new Thread(this,"in").start();  new Thread(this,"out").start();	}  	public void run(){  if(Thread.currentThread().getName().equals("in")){ 	 while(true) 	 try{    String object=(String)in.readUTF();    System.out.println("Otrzymales:"+object); 	 }catch(Exception e){System.out.println("Object had not been read...");}  }  if(Thread.currentThread().getName().equals("out")){ 	 try{    out.writeUTF("Hello from Pawel Steblinski..."); 	 }catch(Exception e){System.out.println("Object had not been read...");} 	   }	}}class MyObject implements Serializable{	String message;	public MyObject(String str){  this.message=str;	}}

Mam powyzszy kod. w funkcji main probuje dodac Frame z buttonem i TextField. Ale w momencie dodania ActionListenera do Button'a

button.addActionListener(this);
- kompilator wyrzuca mi blad:

 

non-static variable this cannot be referenced from a static context

i wskazuje na wyraz THIS w nawiasie

 

O co chodzi?? pytam na forum bo nie mam czasu zeby wczytywac sie teraz w Jave. A jestem dopiero raczkujacym uzytkownikiem tej platformy. Na jutro musze zrobic program (a dokladnie dopisac pare rzeczy do gotowego szkieletu). prosze o pomoc w powyzej opisanej kwestii

Edytowane przez soska66

Udostępnij tę odpowiedź


Odnośnik do odpowiedzi
Udostępnij na innych stronach

a zastanowiles sie co to 'this' znaczy ?

Probujesz w metodzie statyczej (mozliwej do odpalenia bez tworzenia instancji klasy) dobrac sie przez this do takiej instancji - co jest oczywiscie bez sensu.

utworz sobie objekt klasy Server i zamiast this przekaz instancje tego objektu.

 

czyli

button.addActionListener(this);
zamieniasz na

Server server = new Server(11111);    button.addActionListener(server);

gdzie 11111 to jakis port ktory sobie wylosowalem - patrz konstruktor klasy

Udostępnij tę odpowiedź


Odnośnik do odpowiedzi
Udostępnij na innych stronach

mam teraz tak

public class Server implements ActionListener,Runnable {	ServerSocket serversocket;	String sendstring;	TextField t;	public Server(int port){  try{ 	 serversocket=new ServerSocket(port,64000);    }catch(Exception e){System.out.println("Server socket not created...");}  new Thread(this).start();	}		public void run(){  while(true){ 	 System.out.println("Waiting for incoming connection..\n"); 	 try{    Socket socket=serversocket.accept();    new SingleThread(socket); 	 }catch(Exception e){System.out.println("An error occured...\n");}  }	}	public static void main(String args[]){  Server server = new Server(64000);  Frame f=new Frame();  TextField t=new TextField();  f.setBounds(0,0,400,200);  f.setLayout(new GridBagLayout());    t=new TextField("Tu wpisz tresc wiadomosci...");  t.setColumns(40);        f.add(t);    Button button=new Button("Send"); 	   button.addActionListener(server);  f.add(button);  f.show();  int port=0;  if(args.length>0){ 	 try{    port=new Integer(args[0]).intValue(); 	 }catch(Exception e){port=7000;}    new Server(port);  }else{ 	 System.out.println("Usage: java Server por \nExample: java Server 7001\n");  }	}	public void actionPerformed(ActionEvent evt) {    Button b= (Button)evt.getSource();      if(b.getLabel()=="Send")  {  String sendstring=new String("dbehfbue");  }     	 	}class SingleThread implements Runnable{	DataInputStream in;	DataOutputStream out;	public SingleThread(Socket socket){  try{ 	 in=new DataInputStream(socket.getInputStream()); 	 out=new DataOutputStream(socket.getOutputStream());  }catch(Exception e){System.out.println("Streams not initialized...");}    new Thread(this,"in").start();  new Thread(this,"out").start();	}	public void run(){  if(Thread.currentThread().getName().equals("in")){ 	 while(true) 	 try{    String object=(String)in.readUTF();    System.out.println("Otrzymales:"+object); 	 }catch(Exception e){System.out.println("Object had not been read...");}  }  if(Thread.currentThread().getName().equals("out")){ 	 try{    out.writeUTF(new String(sendstring)); 	 }catch(Exception e){System.out.println("Object had not been read...");} 	   }	}}}class MyObject implements Serializable{	String message;	public MyObject(String str){  this.message=str;	}}

przerzucilem klase SingleThread do wnetrza klasy glownej Server.

 

Tworze String sendstring. Jesli nadam mu wartosc na samym poczatku to elegancko dziala i funkcja run() w klasie SingleThread widzi wartosc tego Stringa.

 

Ale gdybym chcial dokonac zmiany wartosci Stringa sendstring w funkcji nacisniecia buttona (actionPerformed), nie nadajac wartosci na poczatku............to tej zmiany funckcja run() w SingleThread juz nie widzi???? na czym polega moj blad?? co porawic

Udostępnij tę odpowiedź


Odnośnik do odpowiedzi
Udostępnij na innych stronach

gdy robisz

public void actionPerformed(ActionEvent evt) {   Button b= (Button)evt.getSource();     if(b.getLabel()=="Send") { String sendstring=new String("dbehfbue"); }       }

to

String sendstring=new String("dbehfbue");
tworzy lokalny w obrebie tego ifa objekt.

 

jesli chesz dopisac sie pod globalna zmienna sendstring to

sendstring=new String("dbehfbue");
lub

this.sendstring=new String("dbehfbue");

dalej kodu nie czytalem wiec nie daje gwarancji ze tylko to jest zwalone

Udostępnij tę odpowiedź


Odnośnik do odpowiedzi
Udostępnij na innych stronach

Dołącz do dyskusji

Możesz dodać zawartość już teraz a zarejestrować się później. Jeśli posiadasz już konto, zaloguj się aby dodać zawartość za jego pomocą.

Gość
Dodaj odpowiedź do tematu...

×   Wklejono zawartość z formatowaniem.   Przywróć formatowanie

  Dozwolonych jest tylko 75 emoji.

×   Odnośnik został automatycznie osadzony.   Przywróć wyświetlanie jako odnośnik

×   Przywrócono poprzednią zawartość.   Wyczyść edytor

×   Nie możesz bezpośrednio wkleić grafiki. Dodaj lub załącz grafiki z adresu URL.

Ładowanie


×
×
  • Dodaj nową pozycję...