• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Prosta aplikacja typu klient-server JavaFx

0 głosów
500 wizyt
pytanie zadane 26 lipca 2017 w Java przez Patryk Rafał Bywalec (2,700 p.)
Witam piszę prostą aplikacje typu klient serwer w javafx i mam problem z wysyłaniem wiadomości z klienta do serwera i odwrotnie udostępniam kod wraz z wyjątkiem może ktoś podpowie co robie nie tak ?

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;

import Network.Network;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @author Patryk
 */
public class ServerMain extends Application {

    @FXML
    private TextArea message;

    @FXML
    private TextField input;

    private boolean isServer = true;
    private Network connection = isServer ? createServer() : null;

    @FXML
    public void initialize() {
        this.input.setOnAction(e -> {

            String message = this.input.getText();
            this.message.appendText(message + "\n");
            this.input.clear();
            try {
                this.connection.send(message);
            } catch (IOException ex) {
               ex.printStackTrace();
            }

        });

    }

    private Parent createContent() throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(this.getClass().getResource("/FXML/ServerFXML.fxml"));
        VBox root = new VBox();
        root = loader.load();
        return root;
    }

    /**
     * ********************************************************************
     */
    @Override
    public void init() {
        this.connection.startConnection();
    }

    /**
     * ********************************************************************
     */
    @Override
    public void stop() throws IOException {
        this.connection.stopConnection();
    }

    /**
     * ********************************************************************
     */
    private Server createServer() {
        return new Server(2015, data -> {
            Platform.runLater(() -> {
                this.message.appendText("Client " + data.toString() + "\n");
            });
        });
    }
    /**
     * ********************************************************************
     */

    @Override
    public void start(Stage primaryStage) throws IOException {
        primaryStage.setTitle("Server");
        primaryStage.setScene(new Scene(createContent()));
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;

import Network.Network;
import java.io.Serializable;
import java.util.function.Consumer;

/**
 *
 * @author Patryk
 */
public class Server extends Network{

    private int port;
    
    public Server(int port,Consumer<Serializable> on) {
        super(on);
        this.port = port;
    }

    @Override
    public boolean isServer() {
        return true;
    }

    @Override
    public int getPort() {
        return this.port;
    }

    @Override
    public String getAdress() {
        return null;
    }
    
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;

import Network.Network;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @author Patryk
 */
public class ClientMain extends Application {

    @FXML
    private TextArea message;

    @FXML
    private TextField input;

    private boolean isServer = false;
    private Network connection = isServer ? null : createClient();

    @FXML
    public void initialize() {
        this.input.setOnAction(e -> {
            String message = this.input.getText();
            this.message.appendText(message + "\n");
            this.input.clear();
            try {
                this.connection.send(message);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            
        });
    }

    private Parent createContent() throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(this.getClass().getResource("/FXML/ClientFXML.fxml"));
        VBox root = new VBox();
        root = loader.load();
        return root;

    }
    
    @Override
    public void init() {
        this.connection.startConnection();
    }

    @Override
    public void stop() throws IOException {
        this.connection.stopConnection();
    }
    
    
    private Client createClient() {
        return new Client("localhost", 2015, data -> {
            Platform.runLater(() -> {
                this.message.appendText("Server " + data.toString() + "\n");
            });
        });
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        primaryStage.setTitle("Client");
        primaryStage.setScene(new Scene(this.createContent()));
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;

import Network.Network;
import java.io.Serializable;
import java.util.function.Consumer;

/**
 *
 * @author Patryk
 */
public class Client extends Network{

    private int port;
    private String adress;
    
    public Client(String a,int p,Consumer<Serializable> on) {
        super(on);
        this.adress = a;
        this.port = p;
    }

    @Override
    public boolean isServer() {
        return false;
    }

    @Override
    public int getPort() {
        return this.port;
    }

    @Override
    public String getAdress() {
        return this.adress;
    }
    
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Patryk
 */
public abstract class Network {

    private Consumer<Serializable> on;
    private clientThread thread = new clientThread();

    public Network(Consumer<Serializable> on) {
        this.on = on;
        this.thread.setDaemon(true);
    }

    public void startConnection() {
        this.thread.start();
    }

    public void stopConnection() throws IOException {
        this.thread.socket.close();
    }

    public void send(Serializable data) throws IOException {
        this.thread.out.writeObject(data); - według wyjątku z tą metodą jest problem
    }

    public abstract boolean isServer();

    public abstract int getPort();

    public abstract String getAdress();

    public class clientThread extends Thread {

        private Socket socket;
        private ObjectOutputStream out;

        @Override
        public void run() {
            try {
                ServerSocket server = isServer() ? new ServerSocket(getPort()) : null;
                Socket socket = isServer() ? server.accept() : new Socket(getAdress(), getPort());
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream is = new ObjectInputStream(socket.getInputStream());

                this.socket = socket;
                this.out = out;

                while (true) {
                    Serializable data = null;

                    data = (Serializable) is.readObject();
                    on.accept(data);

                }

            } catch (Exception ex) {
                System.out.println("Zamykanie");

            }
        }
    }

}

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
	at Network.Network.send(Network.java:41)
	at Client.ClientMain.lambda$initialize$0(ClientMain.java:49)
	at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
	at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
	at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
	at javafx.event.Event.fireEvent(Event.java:198)
	at javafx.scene.Node.fireEvent(Node.java:8413)
	at com.sun.javafx.scene.control.behavior.TextFieldBehavior.fire(TextFieldBehavior.java:179)
	at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callAction(TextInputControlBehavior.java:178)
	at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent(BehaviorBase.java:218)
	at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callActionForEvent(TextInputControlBehavior.java:127)
	at com.sun.javafx.scene.control.behavior.BehaviorBase.lambda$new$74(BehaviorBase.java:135)
	at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
	at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
	at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
	at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
	at javafx.event.Event.fireEvent(Event.java:198)
	at javafx.scene.Scene$KeyHandler.process(Scene.java:3964)
	at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
	at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
	at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
	at java.security.AccessController.doPrivileged(Native Method)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$353(GlassViewEventHandler.java:248)
	at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
	at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
	at com.sun.glass.ui.View.notifyKey(View.java:966)
	at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
	at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
	at java.lang.Thread.run(Thread.java:745)

 

komentarz 28 lipca 2017 przez Patryk Rafał Bywalec (2,700 p.)
Czyli dobrze rozumiem że initialize mam dać do konstruktora ?
komentarz 28 lipca 2017 przez Mateusz51 Nałogowiec (28,220 p.)
Raczej przeniesc pierwsze linijki z run do konstruktora
komentarz 29 lipca 2017 przez Patryk Rafał Bywalec (2,700 p.)
Widzę że nie rozumiesz idei watka proponuje poczytać o tym
komentarz 29 lipca 2017 przez Mateusz51 Nałogowiec (28,220 p.)
Coż wiem o wątkach o wiele wiecej niż tobie się zdaje. Ale rozumiem że musisz sam dojść do swoich problemów.
komentarz 31 lipca 2017 przez Patryk Rafał Bywalec (2,700 p.)
Dobra tamto już rozwiązane

Zaloguj lub zarejestruj się, aby odpowiedzieć na to pytanie.

Podobne pytania

0 głosów
1 odpowiedź 248 wizyt
pytanie zadane 24 maja 2018 w Java przez Darek554 Użytkownik (980 p.)
0 głosów
1 odpowiedź 170 wizyt
pytanie zadane 7 lipca 2019 w Java przez Luki_ Nowicjusz (220 p.)
0 głosów
1 odpowiedź 62 wizyt
pytanie zadane 2 grudnia 2021 w Java przez DzikieHarce Użytkownik (510 p.)

88,364 zapytań

136,964 odpowiedzi

305,691 komentarzy

58,632 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Sklep oferujący ćwiczenia JavaScript, PHP, rozmowy rekrutacyjne dla programistów i inne materiały

Oto dwie polecane książki warte uwagi. Pełną listę znajdziesz tutaj.

...