简体   繁体   中英

Can't access pairs/data of public static Vector<Vector> inside other class?

I'm trying to write one programm with two threads, the first of which receives some UDP-packets and writes the data and a timestamp into a vector with the second supposed to occassionally read from the vector and send it to other pcs via http. The most relevant parts of the code are probably:

public class empfaenger extends Thread {
    public static Vector<Vector> db = new Vector<Vector>();

    public static void main(String[] args) throws IOException {
        //Vector<Vector> db = new Vector<Vector>();                          //previous solution before trying to implement multihreading
        db.add(0, new Vector<String>());
        db.add(1, new Vector<Pair<Integer, Timestamp> >());
        db.add(2, new Vector<Pair<Integer, Timestamp> >());
        db.add(3, new Vector<Pair<Integer, Timestamp> >());

        InetAddress empfangadresse = InetAddress.getByName("127.0.0.1");
        DatagramSocket socketeins = new DatagramSocket(50, empfangadresse);

        httpserverklassetest konkreterserver = new httpserverklassetest();
        konkreterserver.start();

        while (0 != 1) {
        //receive and write data

and

class httpserverklassetest extends Thread{

    //public void httpserverklasse() throws IOException {
    @Override
    public void run() {
        try {
            System.out.println("in anderem thread");

            //for (Pair<Integer, Timestamp> aktpair : empfaenger.db.get(1)) {       //doesn't work
            for (int i = 0; i < empfaenger.db.get(1).size(); i++) {
                empfaenger.db.get(1).get(i).getKey();                               //current code, but doesn't work either
//Intellij doesn't even show the getKey()/marks it red

            }

So the problem seems to be that the run-function doesn't know that the vectors inside the "outer" vector already have specific data-types assigned to them at the start of the main-function, but how could i fix that (if that is the problem)?
(Both threads did work when started as separate programms and also after putting them together multithreaded, but the programm stopped working when trying to iterate through the vector declared inside the first class while being inside the second class/thread.)
Thanks for any help


full code:

import javafx.util.Pair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Vector;


public class empfaenger extends Thread {
    public static Vector<Vector> db = new Vector<Vector>();



    public static void main(String[] args) throws IOException {
        //Vector<Vector<String>> db = new Vector<Vector<String>>();       //geht allein iwie nicht
        //Vector<Vector> db = new Vector<Vector>();
        db.add(0, new Vector<String>());
        db.add(1, new Vector<Pair<Integer, Timestamp> >());
        db.add(2, new Vector<Pair<Integer, Timestamp> >());
        db.add(3, new Vector<Pair<Integer, Timestamp> >());

        InetAddress empfangadresse = InetAddress.getByName("127.0.0.1");
        DatagramSocket socketeins = new DatagramSocket(50, empfangadresse);

        httpserverklassetest konkreterserver = new httpserverklassetest();
        konkreterserver.start();

        while (0 != 1) {



            byte[] empfangbytearray = new byte[65000];                            //ACHTUNG NICHT GANZ GENAU ENTSPRECHEND MAXIMALGRÖßE
            DatagramPacket empfangpaket = new DatagramPacket(empfangbytearray, empfangbytearray.length);
            socketeins.receive(empfangpaket);


            //String teststring = new String(empfangpaket.getData().toString());
            String teststring = new String(empfangbytearray, 0, empfangpaket.getLength());      //von stackoverflow
            System.out.println("bla" + teststring + "bla");


            if (empfangpaket.getPort() == 90) {                                                                             //speicherformat abstimmen

            }
            else if (empfangpaket.getPort() == 91) {
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                Pair<Integer, Timestamp> einfuegepair = new Pair<>( Integer.parseInt(teststring), timestamp);
                db.get(1).addElement(einfuegepair);
            }
            else if (empfangpaket.getPort() == 92){
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                Pair<Integer, Timestamp> einfuegepair = new Pair<>( Integer.parseInt(teststring), timestamp);                                //...
                db.get(2).addElement(einfuegepair);
            }
            else if (empfangpaket.getPort() == 93){
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                Pair<Integer, Timestamp> einfuegepair = new Pair<>( Integer.parseInt(teststring), timestamp);     //Pair<Integer, Timestamp> einfuegepair = new Pair<>( Integer.parseInt(String.valueOf(teststring.charAt(2))), timestamp);                                //...
                //db.get(3).addElement( String.valueOf(teststring.charAt(2)) );                                                                           //db.get(3).get(2 /*db.get(3).size()*/) = String.valueOf(teststring.charAt(3));
                db.get(3).addElement(einfuegepair);
            }
        }

    }
}


class httpserverklassetest extends Thread{

    //public void httpserverklasse() throws IOException {
    @Override
    public void run() {
        try {
            System.out.println("in anderem thread");

            //for (Pair<Integer, Timestamp> aktpair : empfaenger.db.get(1)) {       //geht iwie nicht
            for (int i = 0; i < empfaenger.db.get(1).size(); i++) {
                empfaenger.db.get(1).get(i).getKey();

            }



            ServerSocket testserver = new ServerSocket(80);
            while (true != false) {
                Socket aktclient = testserver.accept();        //accept wartet wohl bis jmd connected und gibt dann diese verbindung zurück


                InputStreamReader isr = new InputStreamReader(aktclient.getInputStream());
                BufferedReader reader = new BufferedReader(isr);
                String line = reader.readLine();


//            if (line.indexOf('?') != -1) {
//                String einschraenkungenstr = line.substring(line.indexOf('?')+1);
//                String akteinschraenkung;
//
//                while (! einschraenkungenstr.isEmpty()){      //not empty oder so;          //war mal aufwändiger gedacht aber gar nicht gefordert daher logik zur argumenteabarbeitung nicht unbedingt notwendig
//                    //if (einschraenkungenstr.charAt(0) == '&') {einschraenkungenstr = einschraenkungenstr.substring(1); }            //ka was remove ist
//                    if (einschraenkungenstr.contains("&")) {
//                        akteinschraenkung = einschraenkungenstr.substring(0, einschraenkungenstr.contains("&");
//                        einschraenkungenstr = einschraenkungenstr.substring(1);                                                       //entferne & ganz am anfang       //alternativ wieder contains und davon dan +1 und dann substring
//                    }
//                    else {akteinschraenkung = einschraenkungenstr;}
//
//                    Integer akteinschraenkunggleichpos = akteinschraenkung.indexOf('=');
//                    String aktkriterium = akteinschraenkung.substring(0, akteinschraenkunggleichpos);
//                    String aktkriteriumwert = akteinschraenkung.substring(akteinschraenkunggleichpos+1);
//
//                    if (aktkriterium == "einzigeskriterium") {                  //a hier ohne mehrargumentlogik da bemerkt dasw wohl nicht zwingend
//                        switch (aktkriteriumwert) {
//                        case "1":
//                            rueck ==
//                            break;
//                        }
//
//                    }
//                    else {
//                        System.out.println("Falsches Kriterium");
//                    }
//
//
//                }
//
//            }


                while (!line.isEmpty()) {                                     //kopiert aus indien zur ausgabe
                    System.out.println(line);
                    line = reader.readLine();
                }
                Date today = new Date();
                String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
                aktclient.getOutputStream().write(httpResponse.getBytes("UTF-8"));

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

db is defined as Vector<Vector>> , so db.get(i).get(j) returns type Object rather than Pair<...> which you're expecting.

Probably what you should use is Vector<Vector<Pair<Integer, Timestamp>>> db = ... , but then you have mixed content, you're adding to db Vector<String> as well as Vector<Pair<...>> .

So either you separate Vectors of Strings and Vectors of pairs conceptually, which I'd recommend, or you check in the loop the class of the content of the vectors, cast and access them accordingly, like

Vector v = empfaenger.db.get(1);
if (v.size() > 0 && v.get(1) instanceof Pair)
{
    Pair<...> p = (Pair<...>) v.get(1);
}

Which I personally find ugly beyond description.

Since you're using the pair-vectors to map port numbers to pairs, you could choose a HashMap<Integer, Pair<...>> portMap for this purpose, giving you the possibility to write

Pair<...> p = portMap.get(empfangpaket.getPort());
if (p != null)
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM