0

I made the source code of UDP server. the task of code shows figure when it received data via UDP communication. I used thread to receive data from other PC via UDP communication.

I use udp test tool from the other PC to check the code.

But, when startup my jar of source code in first, then the udp test tool can't bind the port .

what is the problem of my source code? (In case that I set different values as the bind's port and send port in other PC's udp test tool,then my source code shows successfully the figure.)

package javafxapplication15;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBuilder;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.FlowPaneBuilder;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBoxBuilder;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.stage.Stage;
import javafx.stage.StageBuilder;
import java.io.*;  
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.LabelBuilder;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFieldBuilder;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
import sun.misc.HexDumpEncoder;
public class JavaFXApplication15 extends Application {
    public DatagramSocket receivesocket; 
    public DatagramPacket receivepacket; 
    public DatagramSocket sendsocket;   
    public DatagramPacket sendpacket;    
    public InetSocketAddress remoteAdress;
    public Label     label;
    public Label     label_IP;
    public Label     label_IP_in;
    public TextField tx_IP;
    public Label     label_SENDPORT;
    public Label     label_SENDPORT_in;
    public Label     label_RECEIVEPORT;
    public Label     label_RECEIVEPORT_in;
    public Label     label_status;
    public TextField tx_SENDPORT;
    public TextField tx_RECEIVEPORT;
    public Button    bt_co;
    public Button    bt1;
    public Button    bt2;
    public Button    bt_play ;
    public ObservableList<String> play_num=null;
    public ComboBox<String> comboBox;
    private String    message;  
    private XYChart.Series series;
    private Timeline timer; 
    private ProgressIndicator indicator;
    private static String     s = null;
    private static String    IP = "192.168.101.30"; 
    private static Integer RECEIVEPORT = 8084;     
    public double time_counter=0.0;
    public double torque_receive_value=0.0;
    public byte[] torque_Hex;
    private String text;
    private byte[] buf;
    @Override
    public void start(Stage stage) throws Exception{

/* timer */
         timer = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent event) {

               time_counter = time_counter+1;

            }
        }));
        timer.setCycleCount(Timeline.INDEFINITE);
        timer.play();

       /* Figure*/
              stage.setTitle("Line Chart Sample");
        //defining the axes
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Time [s]");
        yAxis.setLabel("Force [N]");
        //creating the chart
        final LineChart<Number,Number> lineChart = 
                new LineChart<Number,Number>(xAxis,yAxis);

        lineChart.setTitle("Receive Data");
        //defining a series
        series = new XYChart.Series();
        series.setName("Torque");
series.getData().add(new XYChart.Data(0.0,0.0));
         lineChart.getData().add(series);


        VBox root = VBoxBuilder.create().spacing(25).children(lineChart).build();



        Scene scene = new Scene(root);


        recieve_UDP();




        stage = StageBuilder.create().width(640).height(640).scene(scene).title("").build();
        stage.show();
    }


    private void recieve_UDP() throws SocketException, IOException {


        ScheduledService<Boolean> ss = new ScheduledService<Boolean>()
        {
            @Override
            protected Task<Boolean> createTask()
            {

                Task<Boolean> task = new Task<Boolean>()
                {
                    @Override
                    protected Boolean call() throws Exception
                    {
                      receivesocket = null;

                       byte[] receiveBuffer = new byte[1024];
                       receivepacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                       receivesocket = new DatagramSocket(RECEIVEPORT);


                       receivesocket.receive(receivepacket);
                       message = new String(receivepacket.getData(),0, receivepacket.getLength());
                       torque_Hex = receivepacket.getData();
                       System.out.println(message);


                      if(message != "Status:Wait"){
                      Platform.runLater( () ->label_status.setText("Status:Done"));

                      /* show Figure */
                      Platform.runLater( () -> series.getData().add(new XYChart.Data(time_counter,Double.parseDouble( message))));

                      }

                       receivesocket.close();
                      return true;
                    };
                };


                 return task;           
            }

        };
        ss.start();
    }




    public static void main(String[] args) {
        launch(args);
    }
}
kkj
  • 81
  • 1
  • 8
  • Probably not relevant to your actual question, but `if(message != "Status:Wait")` is almost certainly not doing what you want it to do. See http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java. (You were also told this in a [previous question](http://stackoverflow.com/questions/41305781/coding-udp-communication-in-javafx).) – James_D Dec 24 '16 at 04:08
  • Actually , I want to send and receive message via UDP communication . the original source code is not capable of setting same port (send and receive port). I thought the problem is in the receive code. So , the above stated code is receive code that excerpt from original source code(send and receive). – kkj Dec 24 '16 at 04:34
  • BTW: Even if you get a exception, it's probably a good idea to close the `DatagramSocket`. You could use try-with resources for this: `try (DatagramSocket receivesocket = new DatagramSocket(RECEIVEPORT)) {...}`. Also I've no idea why you declare it a field instead of a local variable. After closing it, it should be pretty useless to other methods.... Furthermore, why post 2 runnables on the application thread instead of just one doing both modifications? `() -> {label_status.setText("Status:Done"); series.getData().add(new XYChart.Data(time_counter,Double.parseDouble( message)));}` – fabian Dec 24 '16 at 08:25
  • Thank you for your comment. >Even if you get a exception, it's probably a good idea to close the DatagramSocket I will modify it later. – kkj Dec 24 '16 at 23:14
  • > Also I've no idea why you declare it a field instead of a local variable you are correct. >why post 2 runnables on the application thread instead of just one doing both modifications? – kkj Dec 24 '16 at 23:14
  • I think your way is smarter, I will modify it later . Maybe, there's not directly relevant to communication error in my code(udp communication). but It is very useful information for me. thank you. – kkj Dec 24 '16 at 23:14
  • I want to know whether it is good to set a thread (ScheduledService ss = new ScheduledService()) in recieve_UDP() function or it is not good? – kkj Dec 24 '16 at 23:18

0 Answers0