Java客户端服务器UDP获取错误的包

时间:2017-06-20 23:31:09

标签: java sockets udp client

对于一个小型大学项目,我必须编写服务器和客户端UDP通信代码。

如果客户端发送数据而服务器只读取,一切都很好。一旦我开始从服务器向客户端发送数据,我的小程序就会出错。

public class Sensors {
private static List<Produkt> allSensors = new ArrayList<Produkt>();

public static void main(String[] args) throws Exception {
    //Preparing Our Data
    initSensors();
    //Server Config
    String serverIP = new String();
    BufferedReader eingabe = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("IP Eintragen:");
    serverIP = eingabe.readLine();
    System.out.println("");

    //Preparing Data to Send

    try{
        DatagramSocket serverSocket = new DatagramSocket(1234);
        byte[] receiveData = new byte[4];
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                       receiveData.length);

        for(;;){

            //Sending
            for (Produkt s : allSensors) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ObjectOutputStream os = new ObjectOutputStream(outputStream);
                os.writeObject(s);
                byte[] sendData = outputStream.toByteArray();
                InetAddress ia = InetAddress.getByName(serverIP);
                DatagramPacket sendPacket= new DatagramPacket(sendData,sendData.length,ia,1223);
                serverSocket.send(sendPacket);
                outputStream.close();
            }
            for (Produkt s : allSensors) {
                System.out.println(s);
            }
            //Empfangen
            try{
            serverSocket.receive(receivePacket);
            String sentence = new String( receivePacket.getData(), 0,
                             receivePacket.getLength() );
            System.out.println("RECEIVED: " + sentence);

            }catch(IOException e){

            }
            Thread.sleep(1000);
            reduceValue();
        }

    }catch (IOException e) {
          System.out.println(e);
  }



}

static public void initSensors() {

    allSensors.add(new Produkt("Äpfel", 0, 100, ""));
    allSensors.add(new Produkt("Birnen", 0, 100, ""));
    allSensors.add(new Produkt("Kiwis", 0, 100, ""));
    allSensors.add(new Produkt("Bananen", 0, 100, ""));
    for (Produkt s : allSensors) {
        System.out.print(s.p_name + " : " + s.p_quant + "\n");
    }
}

static public void reduceValue() {
    for (Produkt s : allSensors) {
        if (s.p_quant > 0) {
            s.p_quant -= 20;
        }
    }

}

static public void fillValue() {
    for (Produkt s : allSensors) {
        s.p_quant = 100;
    }
}

}

public class Fridge extends Thread {

private static int port;
private static String htmlInsert = "";
private static DataShare ds;

public Fridge(int port, DataShare ds) {
    this.port = port;
    this.ds = ds;
}

@Override
public void run() {

    System.out.println("Start Fridge Server");

    try {
        handleRequest();
    } catch (Exception ex) {
        Logger.getLogger(Fridge.class.getName()).log(Level.SEVERE, null, ex);
    }

}

static public void handleRequest() throws Exception {
    try{
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] recivingData = new byte[512];

        DatagramPacket receivePacket = new DatagramPacket(recivingData, recivingData.length);


        for(;;)
        {
            if(!ds.produkte.isEmpty()){
                if(ds.produkte.get(0).p_quant == 0){
                    ds.reOrder = true;
                }else{
                    ds.reOrder = false;
                }
            }
            //Empfangen
            serverSocket.receive(receivePacket);
            //prepare Data for conversion into Produkt
            recivingData = receivePacket.getData();
            ByteArrayInputStream in = new ByteArrayInputStream(recivingData);
            ObjectInputStream is = new ObjectInputStream(in);
            Produkt reveivedProdukt = (Produkt) is.readObject();
            //Decoding Produkt into DataShare
            //System.out.println(reveivedProdukt);
            decodeData(reveivedProdukt);
            writeHTML();

            //Senden
            String reorder = new String();
            if(ds.reOrder){
                reorder = "FILL";
            }else{
                reorder ="NOT";
            }
            System.out.println(reorder);
            byte[] sendingDate = reorder.getBytes("UTF-8");
            DatagramPacket sendingPacket = new DatagramPacket(sendingDate, sendingDate.length,
                    receivePacket.getAddress(),receivePacket.getPort());
            serverSocket.send(sendingPacket);

        }

    }catch(IOException e){
        System.out.println(e);
    }catch(ClassNotFoundException e){
        e.printStackTrace();
    }


}

static public void writeHTML() throws Exception {
    List<String> lines = new ArrayList<String>(Arrays.asList("<!DOCTYPE html>\n",
            "<html>\n",
            "   <head>\n",
            "       <meta charset=\"utf-8\">\n",
            "       <title>Test</title>\n",
            "   </head>\n",
            "   <body>\n",
            "\n",
            "       <h1 style=\"color:red;\">Das ist ein Test</h1>\n",
            "\n",
            "   </body>\n",
            "</html>"));
    htmlInsert += "<p>";
    for(Produkt p : ds.produkte){
        htmlInsert+= p.p_name +" Preis: " + p.p_price + " Shopname: "+
                     p.shop_name + " Quantity: " + p.p_quant + "</br>";
    }

    htmlInsert+=  "</p></br>";              
    lines.add(6, htmlInsert);

    /* WINDOWS Path file = Paths.get(".\\src\\HttpServer\\data.html");*/ 
    /* LINUX*/ Path file = Paths.get("/home/debian/GitRepo/VSSS17/Fridge/src/HttpServer/data.html");
    Files.write(file, lines, Charset.forName("UTF-8"));

}

static public void decodeData(Produkt data) {

    Produkt comp = ds.getProduktByName(data.p_name);
    if (!comp.p_name.equals("Fail")) {
        //System.out.println("Changed" + data.p_name + "for amount: " + data.p_quant);
        ds.setQuant(data.p_name, data.p_quant);
    } else {
        ds.addProdukt(data);
    }

    //System.out.println("---");
    if (ds.getLegnth() != 0) {
    //    ds.print();
    }
    //System.out.println("---");

}

}

因此,一旦我从Sensordata的数量为0,我开始发送&#34; FILL&#34;字符串到我的客户端。客户只获得&#34; NOT&#34;包。这将持续大约50个包,直到客户收到&#34; FILL&#34;包。在此之后,服务器正在发送&#34; NOT&#34;包装,因为数量回到100.但客户仍然收到&#34; FILL&#34;包装再次约50包。我有不同的方法,如打开2个插座,一个用于阅读一个用于写作。但它仍然是同一个问题。

我真的不明白为什么它不起作用。无法在互联网上找到它的任何营养。也许你们可以帮助我。

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。我正在向服务器发送4 Packats。服务器正在发送4个数据包。对于我的客户端正在读取数据包的每个循环,他发送了4个新数据包并获得了4个新数据包。所以Stack of Packets刚刚增长。

我把我的客户的阅读和写作分成两个主题。现在它的工作完美