无法从datainputstream JavaFx套接字应用程序

时间:2016-04-20 22:18:14

标签: java image sockets javafx-2

我正在尝试将图像输出到javafx中的ImageView,我通过套接字连接接收图像并将其保存到我的硬盘然后我用新创建的图像的路径创建一个Image对象,问题是图像视图未更新。

public void save(String path, DataInputStream dis) throws IOException {
    FileOutputStream fos = new FileOutputStream("src/img"+(frame_number)+".jpg");


    //Image imBuff = ImageIO.read(socket.getInputStream());

    int filesize = dis.readInt(); // Send file size in separate msg
    byte[] buffer = new byte[filesize];
    int read = 0;
    int totalRead = 0;
    int remaining = filesize;
    while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
        totalRead += read;
        remaining -= read;
        //System.out.println("read " + totalRead + " bytes.");
        fos.write(buffer, 0, read);
        System.err.println("img"+(frame_number)+".jpg");
        fos.flush();
    }
    fos.flush();
    fos.close();

    System.out.println("frame num:"+frame_number);
    Image i = new Image("Camera_Frame.jpg");
    try{
    //i=new Image("img"+frame_number+".jpg");
        File f = new File("img"+frame_number+".jpg");
        i = new Image(f.toURI().toString());
        iv.setImage(i);
    }catch(Exception e){
        System.out.println("didn't find");
    }
    System.out.println("stream size:"+image_Stream.size());
    ps.println("ok");
    frame_number++;
}

我尝试过的事情:
1-我试图使用我保存照片的路径创建一个Image然后在我的ImageView(iv)上使用setImage()函数,即使我之前从同一目录加载了一个图像,我也得到了无效的URL。
2-我们尝试使用(file:///)获取绝对路径,但它不起作用,也是无效的url
3-我尝试首先将图像作为文件加载,然后使用toURI()函数获取正确的路径然后相应地创建图像,我没有得到错误,但它也没有更新UI

P.S 这个函数是在一个子线程中调用的,它在主javafx线程中更新了ImageView,我尝试使用未通过套接字连接加载的图像并且它有效,但是当我尝试显示图像时,我收到面对这个问题。

编辑:我设法正确加载图像,现在我无法使用iv.setImage()

更新ImageView

编辑:
CameraOBJ班
    import java.awt.image.BufferedImage;     import java.io.DataInputStream;     import java.io.File;     import java.io.FileNotFoundException;     import java.io.FileOutputStream;     import java.io.IOException;     import java.io.PrintStream;     import java.net.Socket;     import java.util.LinkedList;     import java.util.Queue;     import java.util.Scanner;

import javax.imageio.ImageIO;

import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.util.Duration;

public class CameraOBJ implements Runnable{
    String name;
    int delay;

    Socket socket;
    String ip;
    int port;
    PrintStream ps;
    Scanner sc;
    static int frame_number;

    StackPane sp;
    Label delay_lbl;
    ImageView iv;

    public CameraOBJ (String name, String ip, int port){
        this.ip = ip;
        this.port = port;
        this.name = name;
        sp = new StackPane();
    }

    public void run() {
        setStackPane();
        connect();
        while(true){
            update();
        }
//      Timeline timeline = new Timeline();
//      Duration duration = Duration.seconds(1/Settings.FPS);
//      KeyFrame f1 = new KeyFrame(duration,e->{
//          update();
//      });
//      timeline.getKeyFrames().add(f1);
//      timeline.setCycleCount(Timeline.INDEFINITE);
//      timeline.play();
    }

    private void update() {
//      Platform.runLater(new Runnable() { 
//          public void run() {
                DataInputStream dis;
                try {
                    dis = new DataInputStream(socket.getInputStream());
                    if(dis!=null){
                        save("images",dis);
                        //setStackPane();
                    }
                } catch (IOException e1) {
                    System.out.println(e1.getMessage());
                }
//          }
//      }); 
    }

    public void setStackPane(){
        Platform.runLater(new Runnable() { 
            public void run() {
                sp.setMinSize(500, 384);
                sp.setMaxSize(500, 384);
                sp.setStyle("-fx-background-color: #FFFFFF;");
                Image image = new Image("Camera_Frame.jpg");
                iv = new ImageView(image);
                iv.setFitWidth(470);
                iv.setPreserveRatio(true);
                Label name_lbl = new Label(name);
                delay_lbl = new Label(delay+"");

                sp.setAlignment(iv,Pos.CENTER);
                sp.setAlignment(name_lbl,Pos.TOP_LEFT);
                sp.setAlignment(delay_lbl,Pos.BOTTOM_RIGHT);

                sp.getChildren().addAll(iv,name_lbl,delay_lbl);                
            }
        });
    }

    public void connect(){
        try{   
            socket = new Socket(ip, port);
            System.out.println(socket.isConnected());

            ps = new PrintStream(socket.getOutputStream());
            sc = new Scanner(socket.getInputStream());
        }
        catch (Exception c){
            c.getMessage();
        }
    }

    public void save(String path, DataInputStream dis) throws IOException {
        Platform.runLater(new Runnable() { 
            public void run() {
            FileOutputStream fos;
            try {
                fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
                int filesize;
                try {
                    filesize = dis.readInt();
                    byte[] buffer = new byte[filesize];
                    int read = 0;
                    int totalRead = 0;
                    int remaining = filesize;
                    while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
                        totalRead += read;
                        remaining -= read;
                        //System.out.println("read " + totalRead + " bytes.");
                        fos.write(buffer, 0, read);
                        System.err.println("img"+(frame_number)+".jpg");
                        fos.flush();
                    }
                    fos.flush();
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } 
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }

        System.out.println("frame num:"+frame_number);
        Image i = new Image("Camera_Frame.jpg");
        try{
            //i=new Image("file:img"+frame_number+".jpg");


            File f = new File("C:\\Users\\ahmed\\workspace\\College\\RTS_Client\\src\\img"+frame_number+".jpg");
            i = new Image(f.toURI().toString());
            iv.setImage(i);
            delay_lbl.setText("frame_number: "+frame_number);
        }catch(Exception e){
            System.out.println("didn't find");
        }

        frame_number++;
        }

        }); 
    }
}

主要课程:

import java.io.File;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import com.sun.prism.paint.Color;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;


public class main extends Application{
    static Stage window;
    static String default_ip = "192.168.43.200";
    static int default_port = 1234;

    public static void main(String[] args) {
        launch(args);
    }

    public void start(Stage stage) {
        window = stage;
        window.setResizable(false);
        window.setTitle("Control Room");

        StackPane sp = new StackPane();
        sp.setMinSize(500, 500);
        Scene sc = new Scene(sp);

        window.setScene(sc);
        window.show();


        CameraOBJ camera = new CameraOBJ("Camera 1", default_ip, default_port);
        Thread t = new Thread(camera);
        camera.run();
        sc = new Scene(camera.sp);
        window.setScene(sc);
    }
}   

服务器类:

import java.io.IOException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Camera implements Runnable {

    long timeStamp;
    int delayShift;
    int FPS;
    boolean idle;
    //Control Rooms object here
    int portNumber;
    Socket csocket;

    Camera() {
    }

    Camera(Socket csocket) {
        this.csocket = csocket;
    }

   void startConnection() throws Exception {
        ServerSocket ssock = new ServerSocket(1234);
        System.out.println("Listening");
        while (true) {
            Socket sock = ssock.accept();
            System.out.println("Connected");
            new Thread(new Camera(sock)).start();
        }
    }

    public void run() {//Start Stream
        try {
            PrintStream pstream = new PrintStream(csocket.getOutputStream());
            Scanner inpstream = new Scanner(csocket.getInputStream());

            // Receiving an integer that is sent from the client side.
            int ID = inpstream.nextInt();
            // Generating a reply based on the ID sent from the client.
            String response = "";
            if (ID == 1100) {
                response = "Your name is Mahmoud. \n" + "You are 22 years old.";
            } else {
                response = "No data found matching the ID you entered.";
            }

            // Sending the reply through the OutputStream to the client.
            pstream.println(response);
            pstream.close();
            terminateConnection();
        } catch (InputMismatchException e) {
            System.out.println(e.toString() + "\nNo data is received.");
        } catch (IOException e) {
            System.out.println(e.toString());
        } catch (Exception c) {
            System.out.println(c.toString());
        }
    }

    void terminateConnection() throws IOException {
        csocket.close();
    }

    public static void main(String[] args) throws Exception {
        Camera cam = new Camera();
        cam.startConnection();
    }

}

0 个答案:

没有答案