将对象从Javafx应用程序传递到控制器,以具有多个线程与控制器

发布于 2025-01-26 22:21:19 字数 8591 浏览 2 评论 0原文

我为自己构建了一个小型的多线程服务器,必须在本地主机上的不同端口上运行它。 基本上,我从“ addMovieApplication”上启动应用程序,“ addmovieyally”是此处的控制器。我启动了我的服务器和客户端,该客户端连接到Onige端口上的服务器以进行稳定连接。我现在需要以某种方式告诉控制器,它必须在哪个套接字上为每个新客户端发送数据。有没有办法将客户端传递到控制器,以便应用程序知道套接字?

控制器

package com.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.model.Movie;
import com.model.MyClient;
import com.view.AddMovieApplication;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

import com.controller.SceneController;

public class AddMovieManually extends SceneController{

    MyClient client = new MyClient();
    @FXML
    public TextField textTitle;
    @FXML
    public TextField textGenre;
    @FXML
    public TextField textPosterSrc;
    @FXML
    public TextField textReleaseDate;
    @FXML
    public TextField textMovieLength;
    @FXML
    public TextField textRegisseur;
    @FXML
    public TextField textAuthor;
    @FXML
    public TextField textCast;

    ArrayList<String> genreList = new ArrayList<>();
    ArrayList<String> authorList = new ArrayList<>();
    ArrayList<String> castList = new ArrayList<>();

    public AddMovieManually() throws IOException {
    }

    @FXML
    public void genreAdd(){
        genreList.add(textGenre.getText());
        textGenre.clear();
    }
    @FXML
    public void authorAdd(){
        authorList.add(textAuthor.getText());
        textAuthor.clear();
    }
    @FXML
    public void castAdd(){
        castList.add(textCast.getText());
        textCast.clear();
    }

    @FXML
    //Checks if the Film already exists, if not, create a new movie Object using the Parameter
    //given from the Textfields and pushes it into the Database. If it already exists take the
    //Movie Object off the database, change the variables and pushes it back in.
    public boolean save()  {
        String title = textTitle.getText();

        String posterSrc = textPosterSrc.getText();
        int releaseDate = Integer.parseInt(textReleaseDate.getText());
        int movieLength = Integer.parseInt(textMovieLength.getText());
        String regisseur = textRegisseur.getText();
        ArrayList<String> genre = this.genreList;
        ArrayList<String> author = this.authorList;
        ArrayList<String> cast = this.castList;


        Movie movie = new Movie(title,posterSrc,releaseDate,movieLength,regisseur,genreList,authorList,castList);
        System.out.println(movie.toString());
        try {
            String jsonMovie = new ObjectMapper().writeValueAsString(movie);
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(this.client.getClientSocket().getOutputStream()));
            pw.println(jsonMovie);
            pw.flush();
            pw.close();
        }catch(Exception e){
            System.out.println("Sending Movie to Server failed ...");
            return false;
        }

        return true;
    }
    @FXML
    //Goes back to the last page without doing anything
    public void abort(){
        switchToSceneWithStage("Login.fxml");
    }



}

应用程序的

public class AddMovieApplication extends Application {



    public void start(Stage stage) throws Exception {
        Scene newScene = new Scene(FXMLLoader.load(getClass().getResource("/addFilmGUI.fxml")));
        //FXMLLoader fxmlLoader = new FXMLLoader(addMovieApplication.class.getResource("addFilmGUI.fxml"));
        //Scene scene = new Scene(fxmlLoader.load());
        stage.setTitle("Here you can manually put in movies");
        stage.setScene(newScene);
        stage.show();


    }
    public static void main() {launch();}
}

客户端我想启动该应用程序时,

package com.model;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;


import com.controller.AddMovieManually;
import com.view.AddMovieApplication;
import com.view.MainAppGUI;



public class MyClient {
    public MyClient() throws IOException  {
        /* for the Login we create a client which requests a connection over port 4 and gets a new
        port for usage from the Server afterwards since we don't have a switch for our Project.*/
        Socket requestSocket = new Socket("localhost", 4999);
        Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(requestSocket.getInputStream())));
        int portForConnection = scanner.nextInt();
        System.out.println("Connected to Server over port : " + portForConnection);
        scanner.close();
        this.clientSocket = new Socket("localhost", portForConnection);
        this.printwriter = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(clientSocket.getOutputStream())));
        this.scanner = new Scanner(new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
    }



    private Socket clientSocket = null;
    final PrintWriter printwriter;
    final Scanner scanner;
    private User user;

    public Socket getClientSocket() { return this.clientSocket; }
    public User getUser() { return this.user; }
    public void setUser(User user) { this.user = user; }










    public static void main(String[] args) throws IOException {
        MyClient client = new MyClient();
        AddMovieApplication.main();
        //AddMovieManually add = new AddMovieManually(client.getClientSocket());

    }


}

我还为您提供服务器的代码,以防万一

package com.model;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class myServer {



    public static void main(String[] args) throws IOException {



        int requestPort = 4999;
        int newClientPort = 5001;



        while (true) {

            ServerSocket serverSocket = new ServerSocket(requestPort);
            /*Create a temporary connection on our request port 10 to send
              a port for stable connection to every Client */

            System.out.println("Waiting for Client ...");
            Socket clientSocketTemp = serverSocket.accept();

            PrintWriter pw = new PrintWriter(new OutputStreamWriter(clientSocketTemp.getOutputStream()));
            pw.println(newClientPort);
            pw.flush();
            serverSocket.close();
            ServerSocket stableConnectedServerSocket = new ServerSocket(newClientPort);
            Socket stableConnectionSocket = stableConnectedServerSocket.accept();
            pw.close();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("[Server] : waiting for input ...");
                    while(stableConnectionSocket.isConnected()) {



                        try {

                            ObjectMapper om = new ObjectMapper();
                            Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(stableConnectionSocket.getInputStream())));
                            PrintWriter pw = new PrintWriter(new OutputStreamWriter(stableConnectionSocket.getOutputStream()));




                            if (scanner.hasNextLine()) {
                                String inputString = scanner.nextLine();
                                System.out.println(inputString);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            System.out.println("create Streams failed");
                            throw new RuntimeException(e);
                        }

                    }


                }
            }).start();

            newClientPort++;
        }

    }
    public static void sendJsonToClient(Scanner input ,PrintWriter output,String userJson){
        output.println(userJson);
        output.flush();
    }
    public static void sendJsonToDatabase(String userJson, int databasePort) throws IOException {
        Socket databaseSocket = new Socket("localhost",databasePort);
        PrintWriter output = new PrintWriter(new OutputStreamWriter(databaseSocket.getOutputStream()));
        output.println(userJson);
        output.flush();
        output.close();
    }




}

I built myself a small multithread Server and have to run it over different ports on my local Host.
Basically I start the Application over "AddMovieApplication", "AddMovieManually" is the Controller here. I Start my Server and my Client, which connects to the server on a onetime port for a stable connection. I somehow need to tell the controller now over which Socket it has to send the data for every new client. Is there a way to pass the client to the controller so that the Application knows the socket?

Controller

package com.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.model.Movie;
import com.model.MyClient;
import com.view.AddMovieApplication;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

import com.controller.SceneController;

public class AddMovieManually extends SceneController{

    MyClient client = new MyClient();
    @FXML
    public TextField textTitle;
    @FXML
    public TextField textGenre;
    @FXML
    public TextField textPosterSrc;
    @FXML
    public TextField textReleaseDate;
    @FXML
    public TextField textMovieLength;
    @FXML
    public TextField textRegisseur;
    @FXML
    public TextField textAuthor;
    @FXML
    public TextField textCast;

    ArrayList<String> genreList = new ArrayList<>();
    ArrayList<String> authorList = new ArrayList<>();
    ArrayList<String> castList = new ArrayList<>();

    public AddMovieManually() throws IOException {
    }

    @FXML
    public void genreAdd(){
        genreList.add(textGenre.getText());
        textGenre.clear();
    }
    @FXML
    public void authorAdd(){
        authorList.add(textAuthor.getText());
        textAuthor.clear();
    }
    @FXML
    public void castAdd(){
        castList.add(textCast.getText());
        textCast.clear();
    }

    @FXML
    //Checks if the Film already exists, if not, create a new movie Object using the Parameter
    //given from the Textfields and pushes it into the Database. If it already exists take the
    //Movie Object off the database, change the variables and pushes it back in.
    public boolean save()  {
        String title = textTitle.getText();

        String posterSrc = textPosterSrc.getText();
        int releaseDate = Integer.parseInt(textReleaseDate.getText());
        int movieLength = Integer.parseInt(textMovieLength.getText());
        String regisseur = textRegisseur.getText();
        ArrayList<String> genre = this.genreList;
        ArrayList<String> author = this.authorList;
        ArrayList<String> cast = this.castList;


        Movie movie = new Movie(title,posterSrc,releaseDate,movieLength,regisseur,genreList,authorList,castList);
        System.out.println(movie.toString());
        try {
            String jsonMovie = new ObjectMapper().writeValueAsString(movie);
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(this.client.getClientSocket().getOutputStream()));
            pw.println(jsonMovie);
            pw.flush();
            pw.close();
        }catch(Exception e){
            System.out.println("Sending Movie to Server failed ...");
            return false;
        }

        return true;
    }
    @FXML
    //Goes back to the last page without doing anything
    public void abort(){
        switchToSceneWithStage("Login.fxml");
    }



}

Application

public class AddMovieApplication extends Application {



    public void start(Stage stage) throws Exception {
        Scene newScene = new Scene(FXMLLoader.load(getClass().getResource("/addFilmGUI.fxml")));
        //FXMLLoader fxmlLoader = new FXMLLoader(addMovieApplication.class.getResource("addFilmGUI.fxml"));
        //Scene scene = new Scene(fxmlLoader.load());
        stage.setTitle("Here you can manually put in movies");
        stage.setScene(newScene);
        stage.show();


    }
    public static void main() {launch();}
}

The Client I want to start the Application when it connects

package com.model;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;


import com.controller.AddMovieManually;
import com.view.AddMovieApplication;
import com.view.MainAppGUI;



public class MyClient {
    public MyClient() throws IOException  {
        /* for the Login we create a client which requests a connection over port 4 and gets a new
        port for usage from the Server afterwards since we don't have a switch for our Project.*/
        Socket requestSocket = new Socket("localhost", 4999);
        Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(requestSocket.getInputStream())));
        int portForConnection = scanner.nextInt();
        System.out.println("Connected to Server over port : " + portForConnection);
        scanner.close();
        this.clientSocket = new Socket("localhost", portForConnection);
        this.printwriter = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(clientSocket.getOutputStream())));
        this.scanner = new Scanner(new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
    }



    private Socket clientSocket = null;
    final PrintWriter printwriter;
    final Scanner scanner;
    private User user;

    public Socket getClientSocket() { return this.clientSocket; }
    public User getUser() { return this.user; }
    public void setUser(User user) { this.user = user; }










    public static void main(String[] args) throws IOException {
        MyClient client = new MyClient();
        AddMovieApplication.main();
        //AddMovieManually add = new AddMovieManually(client.getClientSocket());

    }


}

I also give you the code for the Server just in case

package com.model;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class myServer {



    public static void main(String[] args) throws IOException {



        int requestPort = 4999;
        int newClientPort = 5001;



        while (true) {

            ServerSocket serverSocket = new ServerSocket(requestPort);
            /*Create a temporary connection on our request port 10 to send
              a port for stable connection to every Client */

            System.out.println("Waiting for Client ...");
            Socket clientSocketTemp = serverSocket.accept();

            PrintWriter pw = new PrintWriter(new OutputStreamWriter(clientSocketTemp.getOutputStream()));
            pw.println(newClientPort);
            pw.flush();
            serverSocket.close();
            ServerSocket stableConnectedServerSocket = new ServerSocket(newClientPort);
            Socket stableConnectionSocket = stableConnectedServerSocket.accept();
            pw.close();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("[Server] : waiting for input ...");
                    while(stableConnectionSocket.isConnected()) {



                        try {

                            ObjectMapper om = new ObjectMapper();
                            Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(stableConnectionSocket.getInputStream())));
                            PrintWriter pw = new PrintWriter(new OutputStreamWriter(stableConnectionSocket.getOutputStream()));




                            if (scanner.hasNextLine()) {
                                String inputString = scanner.nextLine();
                                System.out.println(inputString);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            System.out.println("create Streams failed");
                            throw new RuntimeException(e);
                        }

                    }


                }
            }).start();

            newClientPort++;
        }

    }
    public static void sendJsonToClient(Scanner input ,PrintWriter output,String userJson){
        output.println(userJson);
        output.flush();
    }
    public static void sendJsonToDatabase(String userJson, int databasePort) throws IOException {
        Socket databaseSocket = new Socket("localhost",databasePort);
        PrintWriter output = new PrintWriter(new OutputStreamWriter(databaseSocket.getOutputStream()));
        output.println(userJson);
        output.flush();
        output.close();
    }




}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文