3

I have trouble coding UDP communication in JavaFx.

The code is capable of sending message but is not capable of receiving message.

What I should revise in the source code to receive the message?

Here is the source code:

public class JavaFXApplication10 extends Application {

public DatagramSocket receivesocket; 
public DatagramPacket receivepacket; 
public DatagramSocket sendsocket;    
public DatagramPacket sendpacket;   
public InetSocketAddress remoteAdress;

public Label     label_IP;
public TextField tx_IP;
public Label     label_SENDPORT;
public Label     label_RECEIVEPORT;
public TextField tx_SENDPORT;
public TextField tx_RECEIVEPORT;
public Button    bt_co;
public Button    bt_start ;
private String    message; 
private XYChart.Series series; 
private Timeline timer; 
private static String    IP = "192.168.121.23"; 
private static Integer SENDPORT = 12345;       
private static Integer RECEIVEPORT = 12345;    
public double time_counter=0.0;
private String text;
private byte[] b;
@Override

public void start(Stage stage) throws Exception{


    /* text */
     tx_IP = TextFieldBuilder.create().text(IP).build();

    /* text */
    tx_SENDPORT = TextFieldBuilder.create().text(""+SENDPORT).build();

    /* text */
    tx_RECEIVEPORT = TextFieldBuilder.create().text(""+RECEIVEPORT).build();

    /*button */
    bt_co = ButtonBuilder.create().text("Connection")
            .prefWidth(200)
            .alignment(Pos.CENTER)
            .id("connect")
            .build();

    /* button_start */
    bt_start = ButtonBuilder.create().text("START")
            .id("start")
            .build();


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

           time_counter = time_counter+1; // time

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

    /*figure*/
    stage.setTitle("Line Chart Sample");

    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("");

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




    HBox root1 = HBoxBuilder.create().spacing(100).children(tx_IP ,tx_SENDPORT,tx_RECEIVEPORT).build();
    HBox root2 = HBoxBuilder.create().spacing(50).children(bt_co).build();
    HBox root3 = HBoxBuilder.create().spacing(25).children(bt_start).build();
    VBox root4 = VBoxBuilder.create().spacing(25).children(root1,root2,root3,lineChart).build();


    Scene scene = new Scene(root4);

    recieve_UDP();


    scene.addEventHandler(ActionEvent.ACTION,actionHandler);



    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());

                   System.out.println(message);



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


             return task;           
        }

    };
    ss.start();
}



EventHandler<ActionEvent> actionHandler = new EventHandler<ActionEvent>(){
    public void handle (ActionEvent e){


        //////////////////////////////////////////////////////////////////////////////  
        Button src =(Button)e.getTarget();
        text = src.getId(); 
        System.out.println(text);
        b = new byte[5];

        if(text == "connect"){

          String text_IP = tx_IP.getText(); 

          label_IP.setText(text_IP);

          IP = text_IP; 


          String text_SENDPORT = tx_SENDPORT.getText(); 


          label_SENDPORT.setText(text_SENDPORT);

          SENDPORT = Integer.parseInt( text_SENDPORT);

          String text_RECEIVEPORT = tx_RECEIVEPORT.getText(); 

          label_RECEIVEPORT.setText(text_RECEIVEPORT);

          RECEIVEPORT = Integer.parseInt(text_RECEIVEPORT);

        }
        else{


               remoteAdress = new InetSocketAddress(IP, SENDPORT);

       sendsocket = null;


               try {
                   sendsocket = new DatagramSocket();
               } catch (SocketException ex) {
                  Logger.getLogger(JavaFXApplication10.class.getName()).log(Level.SEVERE, null, ex);
               }

               }
               if(text=="start"){

                     b[0] = (byte)0x02;
                     text ="OK";   


               }

               else{

               }


        Send_UDP();
         /////////////////////////////////////////////////////// 
    }
};
public void Send_UDP(){

    /////////////////////////////////////////////////////// 
if(text=="OK"){

            sendpacket = new DatagramPacket(b, b.length,remoteAdress);

            try {

                sendsocket.send(sendpacket);
            } catch (IOException ex) {
                Logger.getLogger(JavaFXApplication10.class.getName()).log(Level.SEVERE, null, ex);
            }

            sendsocket.close();
            text="";

            }
        else {}
        /////////////////////////////////////////////////////// 

}


public static void main(String[] args) {
    launch(args);
}
}
kkj
  • 81
  • 1
  • 8
  • 1
    What do you mean, "not capable?" Do you get an error? Have you stepped through the code in the debugger? – OldProgrammer Dec 23 '16 at 18:54
  • 1
    `if(text == "connect")`, `if(text=="start")`, and `if(text=="OK")` are likely to fail. See http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java . – VGR Dec 23 '16 at 19:33
  • I can send the message from PC A that is executed this source code to PC B that is used UDP test tool . But I can't receive the message from PC A that is executed this source code to PC B(that is used UDP test tool. I can't get the message . Additionally, I can't use the same port(send port and receive port). – kkj Dec 23 '16 at 23:09
  • thank you for your valuable comment , I revise the code as the following: ex: text.equals("OK") . But, the UDP Communication doesn't succeed. – kkj Dec 23 '16 at 23:26
  • I can communicate with PC A and PCB in case that I set the different port number. but I I can't communicate with PC A and PCB in case that I set the same port number(receive port and send port). – kkj Dec 24 '16 at 01:27

1 Answers1

2

You code is really fuzzy, maybe I don't understand the purpose of all those code blocks but I can tell you UDP communication is pretty simple, let me first throw some quick light on way UDP communication works:

UDP communication refresher

Please note that I have used only some code snippets below for demonstration so kindly do not look then for completeness, complete code can be found in the code I have pasted in end.

  • UDP can be used for unicast as well as multicast communication. If UDP is used for unicast communication then there will always be a UDP client requesting something from a UDP server, however if UDP is used for multicast communication then UDP server will multicast/broadcast the message to all listening UDP clients.
  • (I will now talk more about UDP unicast) A UDP server will be listening on a network port for client requests DatagramSocket socket = new DatagramSocket(8002); socket.receive(packet);

  • A UDP client want to communicate with a UDP server, so it opens a DatagramSocket and send a DatagramPacket over it. DatagramPacket will contain the endpoints of the UDP server.

  • Once UDP client has sent the message using socket.send(packet);, it will then prepare to receive for the response from UDP server, using socket.receive(packet); (I think this where you are missing) Most important thing to understand is that if client doesn't prepare for receiving then it will not be able to get what UDP server would send because in case of UDP there is no connection between UDP client and UDP server, so UDP must be listening after sending the message.
  • UDP server will receive the request from UDP client, will process the request and will send using sendingDatagramSocket.send(packet);. It will prepare the DatagramPacket using the response and endpoints of the UDP client.
  • UDP client which is listening, as mentioned in above step socket.receive(packet); will get the response from UDP server. Important thing to note here is that if UDP client is not listening OR not listening on same port which it has opened while making the request (basically using the same DatagramSocket object used for sending the request) then UDP client will never receive whatever UDP server is going to send.

Answer to OP's questions

Main issue is that in Send_UDP you are only sending but not receiving and in recieve_UDP you are only receiving but not sending.

So, basically you need to both send and receive in UDP client and UDP server, its just that it would be vice-versa but you need to do both the things.

Sample UDP server and UDP client

UDP client:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

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

        // get a datagram socket
        DatagramSocket socket = new DatagramSocket();
        System.out.println("### socket.getLocalPort():" + socket.getLocalPort() + " | socket.getPort(): " + socket.getPort());

        // send request
        byte[] buf = "Hello, I am UDP client".getBytes();
        InetAddress address = InetAddress.getByName("localhost");
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 8002);
        socket.send(packet);

        // get response
        packet = new DatagramPacket(buf, buf.length);
        System.out.println("Waiting to receive response from server." + new Date());
        socket.receive(packet);
        System.out.println("Got the response back from server." + new Date());

        // display response
        String received = new String(packet.getData());
        System.out.println("Quote of the Moment: " + received);

        socket.close();
    }
}

UDP server:

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

public class SimpleUDPServer {

    public static void main(String[] args) throws SocketException, InterruptedException {
        DatagramSocket socket = new DatagramSocket(8002);

        while (true) {
            try {
                byte[] buf = new byte[256];

                // receive request
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                System.out.println("### socket.getLocalPort():" + socket.getLocalPort() + " | socket.getPort(): " + socket.getPort());

                // figure out response
                String dString = "Server is responding:  asd  asdd";
                buf = new byte[256];
                buf = dString.getBytes();

                // send the response to the client at "address" and "port"
                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                System.out.println("Data from client: " + new String(packet.getData()));
                packet = new DatagramPacket(dString.getBytes(), dString.getBytes().length, address, port);
                System.out.println("### Sending for packet.hashCode(): " + packet.hashCode() + " | packet.getPort(): " + packet.getPort());

                //Thread.sleep(5000);

                System.out.println("Now sending the response back to UDP client.");

                DatagramSocket sendingDatagramSocket = new DatagramSocket();
                sendingDatagramSocket.send(packet);
                sendingDatagramSocket.close();
                System.out.println("I am done");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Further readings

I strongly recommend read this Java tutorial, if not complete then at-least "Writing a Datagram Client and Server" section.

hagrawal7777
  • 14,103
  • 5
  • 40
  • 70