在 JavaFx 中编码 UDP 通信 [英] coding UDP communication in JavaFx

查看:38
本文介绍了在 JavaFx 中编码 UDP 通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JavaFx 中编写 UDP 通信时遇到问题.

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?

这是源代码:

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

推荐答案

你的代码真的很模糊,可能我没看懂所有这些代码块的用途,但我可以告诉你 UDP 通信很简单,让我先快速了解 UDP 通信的工作方式:

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 可用于单播和多播通信.如果 UDP 用于单播通信,那么总会有一个 UDP 客户端向 UDP 服务器请求某些东西,但是如果 UDP 用于多播通信,则 UDP 服务器会将消息多播/广播给所有侦听的 UDP 客户端.
  • (我现在将详细讨论 UDP 单播) UDP 服务器将在网络端口上侦听客户端请求 DatagramSocket socket = new DatagramSocket(8002);socket.receive(packet);

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

UDP 客户端想要与 UDP 服务器通信,因此它打开一个 DatagramSocket 并通过它发送一个 DatagramPacket.DatagramPacket 将包含 UDP 服务器的端点.

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.

主要问题是在 Send_UDP 中你只发送但不接收,而在 recieve_UDP 中你只接收但不发送.

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.

所以,基本上你需要在 UDP 客户端和 UDP 服务器中发送和接收,只是反之亦然,但你需要同时做这两件事.

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.

UDP 客户端:

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 服务器:

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

}

进一步阅读

我强烈建议阅读这个 Java 教程,如果不完整,那么至少编写数据报客户端和服务器"部分.

Further readings

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

这篇关于在 JavaFx 中编码 UDP 通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆