Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 26

Thread: Threads and Sockets

  1. #1
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Threads and Sockets

    Hey I could use some help again.

    I'm working with some threads and sockets for my Torrent Client over TCP.

    I have a main Thread Class (PeerManager) that is creating an ArrayList of a second Thread class (PeerConnect).

    PeerManager will create PeerConnect Threads untill there is 25 of them or it runs out of peers to connect too.

    I have an ArrayList for all the peers and also an ArrayList for the index of peers that have running Threads and the peers that do not. These are named "connected" and "notconnected".

    All the PeerConnect threads do right now is try to open a socket with thire given IP and Port number.

    The threads are named by the ID of the peer and not by creation order. The peer they try to connect too is chosen randomly by the roolpeer() method from the notconnected Arraylist.

    I seem to be having two problems...

    The first few Thread seem to create the socket just fine. Then the rest throw java.net.ConnectException: "Connection timed out: connect" and "Connection refused: connect" errors.

    As the first few always connect just fine and are chosen randomly, is there some kind of limit to the number of sockets I can open?

    The second problem is with a thread flag called Blacklist in the peerconnect class.

    I set it so the flag would be set true if some kind of connection error dose come up in the peerconnect threads. That peer can be temporally black listed and dealt with later.

    The PeerManager is checking for this flag in a for loop so it can black list the peer.

    By the output I can see the flag is being set true but the if statement that black lists the peer never seems to run. You can also see that once the error messages start to come in on the output the "loop marker" System.out message stops being printed. I checked with a System.out... by this point the main while loop of the PeerManager class is no longer running so the program no longer get too the blacklist for loop.

    The black list flag is set as volatile and I have tried synchronising its setter and geter.

    There is also a Pieceno variable setting up a Static ArrayList "Blocklist" in the peerconnect class. You can see this being set in the PeerManager. Its just a list of each block to be downloaded. Other than it being initialised it's not part of the logic yet.

    The PeerManager Thread Class
    import java.util.ArrayList;
    import java.util.Random;
     
    public class PeerManager extends Thread {
     
        int ID;
     
        ArrayList<PeerConnect> peerconnection = new ArrayList<PeerConnect>();
     
        ArrayList<String> peerlist = new ArrayList<String>();
        ArrayList<Integer> connected = new ArrayList<Integer>();
        ArrayList<Integer> notconnected = new ArrayList<Integer>();
        ArrayList<Integer> blacklist = new ArrayList<Integer>();
     
        String infohash;
     
        //flag for a static variable
        boolean flipblocklist = false;
     
        ArrayList<Long> downspeed = new ArrayList<Long>();
        long pieceno = 0;
        boolean[] donelist;
     
        FileManager fileManager;
     
     
    public PeerManager(ArrayList<String> array, boolean mode, ArrayList<Long> length, ArrayList<String> path, int piecelength, int nopieces, int slength, String pieces, String hash, int pid){
            //Constructor just passing variables
     
            //System.out.println("Peer Management created");
            peerlist = (ArrayList<String>)array.clone();
     
            for (int i = 0; i < peerlist.size(); i++){
                notconnected.add(i);
            }
     
            ID = pid;
     
            setPieceno(nopieces);
     
            infohash = hash;
     
            fileManager = new FileManager(mode, length, path, piecelength, nopieces, slength, pieces, pid);
        }
     
     
        @Override
        public void run() {
     
            //main while loop
            while (true){
                if (connected.size() < 20 && notconnected.size() > 0){
                    int last;
                    peerconnection.add(new PeerConnect());
     
                    //index of current object
                    last = peerconnection.size() - 1;
     
                    //select random peer and update lists
                    int newpeer = roolpeer();
                    peerconnection.get(last).setPeerin(peerlist.get(newpeer));
                    connected.add(newpeer);
                    int remove;
                    remove = notconnected.indexOf(newpeer);
                    notconnected.remove(remove);
     
                    peerconnection.get(last).setName(Integer.toString(newpeer));
                    peerconnection.get(last).setNamein(Integer.toString(newpeer));
                    peerconnection.get(last).setInfohash(infohash);
                    peerconnection.get(last).start();
     
     
                    //setting of static variable during the first peerconnect object only
                    if (!flipblocklist){
     
                        //System.out.println();
                        //System.out.println("NO Of Pieces: " + getPieceno());
                        //System.out.println("Block List: ");
     
                        for (int i = 0; i < getPieceno(); i ++){
                            peerconnection.get(0).setBlocklist(i);
                            //System.out.println(peerconnection.get(0).getBlocklist(i));
                        }
                        flipblocklist = true;
                    }
     
                    //--------end of peerconnection creation
     
                    System.out.println("loop Run Marker-------------------------loop Run Marker");
     
                    //------blacklist bad sockets----------------------
                    for (int i = 0; i < peerconnection.size(); i++){
                        if (peerconnection.get(i).getBlacklist() == true){
                            // This block of code never seems to run
                            System.out.println("------------blackllop running");
                            String holdname = peerconnection.get(i).getPeerin();
                            peerconnection.remove(i);
                            connected.remove(Integer.valueOf(holdname));
                            blacklist.add(Integer.valueOf(holdname));
                            System.out.println("Peer: " + holdname + " was Blacklisted");
                        }
                    }
                }
     
     
            }
     
     
     
        }
        public long getPieceno() {
            return pieceno;
        }
     
        public void setPieceno(long pieceno) {
            this.pieceno = pieceno;
            int temp = (int) this.pieceno;
            donelist = new boolean[temp];
     
            for (int i = 0; i < donelist.length; i ++){
                donelist[i] = false;
            }
        }
     
        public int roolpeer(){
            //Picks a random peer
     
            int ID;
     
            Random rand = new Random();
            int n = rand.nextInt(notconnected.size());
     
            ID = notconnected.get(n);
     
            return ID;
        }
    }

    The PeerConnect ThreadClass
     
    import java.net.Socket;
    import java.util.ArrayList;
    import java.net.*;
    import java.io.*;
     
    public class PeerConnect extends Thread {
     
        String namein;
        String peerin;
        String IP;
        int port;
     
        String infohash;
     
        volatile boolean Blacklist = false;
     
        //-------Socket Variables -----------
        private Socket clientSocket;
        private BufferedOutputStream out;
        private BufferedInputStream in;
        //--------------------------------
     
        static volatile ArrayList<Integer> blocklist = new ArrayList<Integer>();
     
        @Override
        public void run() {
            System.out.println("Thread ID: Peer " + Thread.currentThread().getName() + " -- Created");
            System.out.println("Peer Info: " + getPeerin());
            peersplit();
            //System.out.println("IP: " + IP);
            //System.out.println("Port: " + port);
            startConnection();
            //stopConnection();
        }
     
        public String getNamein() {
            return namein;
        }
     
        public void setNamein(String namein) {
            this.namein = namein;
        }
     
        public String getPeerin() {
            return peerin;
        }
     
        public void setPeerin(String peerin) {
            this.peerin = peerin;
        }
     
        public synchronized static int getBlocklist(int object) {
            int index = blocklist.indexOf(object);
            int output = blocklist.get(index);
     
            return output;
        }
     
        public synchronized boolean getBlacklist() {
            return Blacklist;
        }
     
        public synchronized void setBlacklist(boolean blacklist) {
            Blacklist = blacklist;
        }
     
        public static void removeBlocklist(int object){
            int index = blocklist.indexOf(object);
            blocklist.remove(index);
        }
     
        public static void setBlocklist(int item) {
            blocklist.add(item);
        }
     
        public String getInfohash() {
            return infohash;
        }
     
        public void setInfohash(String infohash) {
            this.infohash = infohash;
        }
     
        public void peersplit(){
            String hold = peerin;
            int index = hold.indexOf(":");
            IP = hold.substring(0, index);
            port = Integer.valueOf(hold.substring(index + 1));
     
        }
     
        public void startConnection() {
     
            boolean catchflip = true;
     
            try {
                clientSocket = new Socket(IP, port);
                out = new BufferedOutputStream(clientSocket.getOutputStream());
                in = new BufferedInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                //System.out.println("Thread: " + Thread.currentThread().getName());
                catchflip = false;
                setBlacklist(true);
                System.out.println("Thread: " + Thread.currentThread().getName() + " ---Blacklist Flip");
                e.printStackTrace();
            } catch (IOException e) {
                //System.out.println("Thread: " + Thread.currentThread().getName());
                catchflip = false;
                setBlacklist(true);
                System.out.println("Thread: " + Thread.currentThread().getName() + " ---Blacklist Flip");
                e.printStackTrace();
            }
            if (catchflip) System.out.println("Thread: " + Thread.currentThread().getName() + " Created a Socket Successfully...");
     
        }
        public void stopConnection() {
            try {
                in.close();
                out.close();
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Thread: " + Thread.currentThread().getName() + " Socket Closed");
        }
    }

    All of the variables being passed in are just coming from a Torrent class in Main. Other then the Peerlist itself none of them are really part of the logic yet.

    Here is that clip from Main anyway...
    torrentList.List.get(lastindex).peerManager = new PeerManager(
                            torrentList.List.get(lastindex).tracker.peers.peerlist,
                            torrentList.List.get(lastindex).getFileMode(),
                            torrentList.List.get(lastindex).getLengthM(),
                            torrentList.List.get(lastindex).getPath(),
                            torrentList.List.get(lastindex).getPieceLength(),
                            torrentList.List.get(lastindex).getNofPieces(),
                            torrentList.List.get(lastindex).getLength(),
                            torrentList.List.get(lastindex).getPieces(),
                            torrentList.List.get(lastindex).tracker.getInfohash(),
                            lastindex
                    );


    Here is the output
    loop Run Marker-------------------------loop Run Marker
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 26 -- Created
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 9 -- Created
    Peer Info: 196.180.223.215:53525
    Peer Info: 197.239.73.94:49160
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 19 -- Created
    Peer Info: 160.120.226.224:45377
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 15 -- Created
    Peer Info: 154.68.5.123:24607
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 17 -- Created
    Peer Info: 196.121.53.141:36156
    Thread ID: Peer 25 -- Created
    Peer Info: 158.222.224.153:566
    Thread ID: Peer 6 -- Created
    Peer Info: 41.83.31.181:24875
    loop Run Marker-------------------------loop Run Marker
    loop Run Marker-------------------------loop Run Marker
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 2 -- Created
    Peer Info: 82.252.143.235:27418
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 18 -- Created
    Peer Info: 184.173.3.24:6969
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 13 -- Created
    Peer Info: 185.149.90.38:51019
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 23 -- Created
    Peer Info: 190.130.154.222:34532
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 12 -- Created
    Peer Info: 185.221.222.115:64842
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 4 -- Created
    Peer Info: 41.202.86.118:49031
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 14 -- Created
    Peer Info: 154.72.171.21:62348
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 8 -- Created
    Peer Info: 200.114.100.3:46040
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 10 -- Created
    Peer Info: 195.199.249.225:17815
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 5 -- Created
    Peer Info: 41.140.48.48:49689
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 7 -- Created
    Peer Info: 37.135.142.160:50160
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 20 -- Created
    Peer Info: 154.66.174.122:49160
    Thread ID: Peer 22 -- Created
    Peer Info: 188.120.129.103:50304
    Thread: 13 Created a Socket Successfully...
    Thread: 4 Created a Socket Successfully...
    Thread: 17 Created a Socket Successfully...
    Thread: 7 ---Blacklist Flip
    java.net.ConnectException: Connection refused: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    Thread: 5 ---Blacklist Flip
    java.net.ConnectException: Connection refused: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    Thread: 26 ---Blacklist Flip
    java.net.ConnectException: Connection refused: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    Thread: 8 ---Blacklist Flip
    java.net.ConnectException: Connection refused: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    Thread: 20 ---Blacklist Flip
    java.net.ConnectException: Connection refused: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    Thread: 9 ---Blacklist Flip
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    Thread: 23 ---Blacklist Flip
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    Thread: 14 ---Blacklist Flip
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)Thread: 10 ---Blacklist Flip
    Thread: 18 ---Blacklist Flip
     
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    Thread: 15 ---Blacklist Flip
    Thread: 25 ---Blacklist Flip
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)Thread: 2 ---Blacklist Flip
     
    Thread: 19 ---Blacklist Flip
    java.net.ConnectException: Connection timed out: connect
    Thread: 6 ---Blacklist Flip
    Thread: 12 ---Blacklist Flip
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    Thread: 22 ---Blacklist Flip
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)
    java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:98)
    	at PeerConnect.run(PeerConnect.java:33)

  2. #2
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Ok so I know now that whats going on is all the thread are running in parallel. So the connected sockets are not the first to be created they are the first to return for creating the socket as they connected quickly.

    Also pretty sure my inputs and outputs where incorrect and I should have been using the DataOutputStream and DataInputStream. So I fixed that.

    So the only question let if why is my main while loop in the PeerManager class stopping?

    Here is the updated peerconnect class
    import java.net.Socket;
    import java.util.ArrayList;
    import java.net.*;
    import java.io.*;
     
    public class PeerConnect extends Thread {
     
        String namein;
        String peerin;
        String IP;
        int port;
     
        String infohash;
     
        volatile boolean Blacklist = false;
     
        //-------Socket Variables -----------
        Socket clientSocket;
        DataOutputStream out;
        DataInputStream in;
        //--------------------------------
     
        static volatile ArrayList<Integer> blocklist = new ArrayList<Integer>();
     
        @Override
        public void run() {
            System.out.println("Thread ID: Peer " + Thread.currentThread().getName() + " -- Created");
            System.out.println("Peer Info: " + getPeerin());
            peersplit();
            //System.out.println("IP: " + IP);
            //System.out.println("Port: " + port);
            startConnection();
            //stopConnection();
        }
     
        public String getNamein() {
            return namein;
        }
     
        public void setNamein(String namein) {
            this.namein = namein;
        }
     
        public String getPeerin() {
            return peerin;
        }
     
        public void setPeerin(String peerin) {
            this.peerin = peerin;
        }
     
        public synchronized static int getBlocklist(int object) {
            int index = blocklist.indexOf(object);
            int output = blocklist.get(index);
     
            return output;
        }
     
        public synchronized boolean getBlacklist() {
            return Blacklist;
        }
     
        public synchronized void setBlacklist(boolean blacklist) {
            Blacklist = blacklist;
        }
     
        public static void removeBlocklist(int object){
            int index = blocklist.indexOf(object);
            blocklist.remove(index);
        }
     
        public static void setBlocklist(int item) {
            blocklist.add(item);
        }
     
        public String getInfohash() {
            return infohash;
        }
     
        public void setInfohash(String infohash) {
            this.infohash = infohash;
        }
     
        public void peersplit(){
            String hold = peerin;
            int index = hold.indexOf(":");
            IP = hold.substring(0, index);
            port = Integer.valueOf(hold.substring(index + 1));
     
        }
     
        public void startConnection() {
     
            boolean catchflip = true;
     
            try {
                clientSocket = new Socket(IP, port);
                out = new DataOutputStream(clientSocket.getOutputStream());
                in = new DataInputStream(clientSocket.getInputStream());
                stopConnection();
            } catch (UnknownHostException e) {
                //System.out.println("Thread: " + Thread.currentThread().getName());
                catchflip = false;
                setBlacklist(true);
                System.out.println("Thread: " + Thread.currentThread().getName() + " ---Blacklist Flip");
                //e.printStackTrace();
            } catch (IOException e) {
                //System.out.println("Thread: " + Thread.currentThread().getName());
                catchflip = false;
                setBlacklist(true);
                System.out.println("Thread: " + Thread.currentThread().getName() + " ---Blacklist Flip");
                //e.printStackTrace();
            }
            if (catchflip) System.out.println("Thread: " + Thread.currentThread().getName() + " Created a Socket Successfully...");
     
        }
        public void stopConnection() {
            try {
                in.close();
                out.close();
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Thread: " + Thread.currentThread().getName() + " Socket Closed");
        }
    }

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    How can anyone test the code? I do not see a main method.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Quote Originally Posted by Norm View Post
    How can anyone test the code? I do not see a main method.
    For main to run you would need a bunch of other classes. You want me to post them all? I would need to post basically the whole package.
    Last edited by Blick; August 24th, 2019 at 02:55 AM.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    No, don't post a bunch of classes. Make a special class for doing testing with.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Here is the PeerManager, PeerConnect and temp Main code. I think there are a few long tearm seeds in that peer list so it should be good for a while. If all the seeds expire just let me know and I can post a new list.

    Main:
    import java.util.ArrayList;
     
    public class Main {
     
        public static void main(String[] args) {
            int pid = 0;
            int Noofpieces = 91;
            String infohash = "5805199A9917AEFA79412656663DCEF23557229F";
     
            ArrayList<String> peerlist = new ArrayList<String>() {
                {
                    add("184.173.25.76:1337");
                    add("160.120.31.143:62348");
                    add("154.66.174.122:49160");
                    add("125.237.79.196:14496");
                    add("105.156.50.188:49689");
                    add("102.165.233.65:7000");
                    add("94.110.174.139:60287");
                    add("80.98.128.175:42176");
                    add("80.77.191.37:47908");
                    add("41.188.104.30:54622");
                    add("41.114.205.238:28508");
                    add("41.96.8.109:21592");
                    add("41.83.197.59:24875");
                    add("37.135.142.160:50160");
                    add("200.114.100.3:46040");
                    add("196.121.53.141:36156");
                    add("197.239.73.94:49160");
                    add("195.199.249.225:17815");
                    add("185.221.222.115:64842");
                    add("185.149.90.38:51019");
                    add("159.253.131.188:44325");
                    add("167.60.208.20:36755");
                }
            };
     
            PeerManager peermanager = new PeerManager(peerlist, Noofpieces, infohash, pid);
     
            peermanager.start();
        }
    }

    PeerManager:
    import java.util.ArrayList;
    import java.util.Random;
     
    public class PeerManager extends Thread {
     
        int ID;
     
        ArrayList<PeerConnect> peerconnection = new ArrayList<PeerConnect>();
     
        ArrayList<String> peerlist = new ArrayList<String>();
        ArrayList<Integer> connected = new ArrayList<Integer>();
        ArrayList<Integer> notconnected = new ArrayList<Integer>();
        ArrayList<Integer> blacklist = new ArrayList<Integer>();
     
        String infohash;
     
        //flag for a static variable
        boolean flipblocklist = false;
     
        ArrayList<Long> downspeed = new ArrayList<Long>();
        long pieceno = 0;
        boolean[] donelist;
     
        public PeerManager(ArrayList<String> array, int nopieces, String hash, int pid){
            //just passing variables
     
            //System.out.println("Peer Management created");
            peerlist = (ArrayList<String>)array.clone();
     
            for (int i = 0; i < peerlist.size(); i++){
                notconnected.add(i);
            }
     
            ID = pid;
     
            setPieceno(nopieces);
     
            infohash = hash;
     
        }
     
     
        @Override
        public void run() {
     
            while (true){
                if (connected.size() < 20 && notconnected.size() > 0){
                    int last;
                    peerconnection.add(new PeerConnect());
     
                    //index of current object
                    last = peerconnection.size() - 1;
     
                    //select random peer and update lists
                    int newpeer = roolpeer();
                    peerconnection.get(last).setPeerin(peerlist.get(newpeer));
                    connected.add(newpeer);
                    int remove;
                    remove = notconnected.indexOf(newpeer);
                    notconnected.remove(remove);
     
                    peerconnection.get(last).setName(Integer.toString(newpeer));
                    peerconnection.get(last).setNamein(Integer.toString(newpeer));
                    peerconnection.get(last).setInfohash(infohash);
     
                    peerconnection.get(last).start();
     
                    //setting of static variable during the first peerconnect object only
                    if (!flipblocklist){
     
                        //System.out.println();
                        //System.out.println("NO Of Pieces: " + getPieceno());
                        //System.out.println("Block List: ");
     
                        for (int i = 0; i < getPieceno(); i ++){
                            peerconnection.get(0).setBlocklist(i);
                            //System.out.println(peerconnection.get(0).getBlocklist(i));
                        }
                        flipblocklist = true;
                    }
     
                    //--------end of peerconnection creation
     
                    System.out.println("loop Run Marker-------------------------loop Run Marker");
     
                    //------blacklist bad sockets----------------------
                    for (int i = 0; i < peerconnection.size(); i++){
                        //System.out.println("Thread: " + i + " is " + peerconnection.get(i).getBlacklist());
                        if (peerconnection.get(i).getBlacklist() == true){
                            // This block of code never seems to run
                            System.out.println("------------blackloop running");
                            String holdname = peerconnection.get(i).getPeerin();
                            peerconnection.remove(i);
                            connected.remove(Integer.valueOf(holdname));
                            blacklist.add(Integer.valueOf(holdname));
                            System.out.println("Peer: " + holdname + " was Blacklisted");
                        }
                    }
                }
     
     
            }
     
     
     
        }
        public long getPieceno() {
            return pieceno;
        }
     
        public void setPieceno(long pieceno) {
            this.pieceno = pieceno;
            int temp = (int) this.pieceno;
            donelist = new boolean[temp];
     
            for (int i = 0; i < donelist.length; i ++){
                donelist[i] = false;
            }
        }
     
        public int roolpeer(){
            //Picks a random peer
     
            int ID;
     
            Random rand = new Random();
            int n = rand.nextInt(notconnected.size());
     
            ID = notconnected.get(n);
     
            return ID;
        }
    }

    PeerConnect:

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
     
    public class PeerConnect extends Thread {
     
        String namein;
        String peerin;
        String IP;
        int port;
     
        String infohash;
     
        volatile boolean Blacklist = false;
     
        //-------Socket Variables -----------
        Socket clientSocket;
        DataOutputStream out;
        DataInputStream in;
        //--------------------------------
     
        static volatile ArrayList<Integer> blocklist = new ArrayList<Integer>();
     
        @Override
        public void run() {
            System.out.println("Thread ID: Peer " + Thread.currentThread().getName() + " -- Created");
            System.out.println("Peer Info: " + getPeerin());
            peersplit();
            //System.out.println("IP: " + IP);
            //System.out.println("Port: " + port);
            startConnection();
            //stopConnection();
        }
     
        public String getNamein() {
            return namein;
        }
     
        public void setNamein(String namein) {
            this.namein = namein;
        }
     
        public String getPeerin() {
            return peerin;
        }
     
        public void setPeerin(String peerin) {
            this.peerin = peerin;
        }
     
        public synchronized static int getBlocklist(int object) {
            int index = blocklist.indexOf(object);
            int output = blocklist.get(index);
     
            return output;
        }
     
        public synchronized boolean getBlacklist() {
            return Blacklist;
        }
     
        public synchronized void setBlacklist(boolean blacklist) {
            Blacklist = blacklist;
        }
     
        public static void removeBlocklist(int object){
            int index = blocklist.indexOf(object);
            blocklist.remove(index);
        }
     
        public static void setBlocklist(int item) {
            blocklist.add(item);
        }
     
        public String getInfohash() {
            return infohash;
        }
     
        public void setInfohash(String infohash) {
            this.infohash = infohash;
        }
     
        public void peersplit(){
            String hold = peerin;
            int index = hold.indexOf(":");
            IP = hold.substring(0, index);
            port = Integer.valueOf(hold.substring(index + 1));
     
        }
     
        public void startConnection() {
     
            boolean catchflip = true;
     
            try {
                clientSocket = new Socket(IP, port);
                out = new DataOutputStream(clientSocket.getOutputStream());
                in = new DataInputStream(clientSocket.getInputStream());
                stopConnection();
            } catch (UnknownHostException e) {
                //System.out.println("Thread: " + Thread.currentThread().getName());
                catchflip = false;
                setBlacklist(true);
                System.out.println("Thread: " + Thread.currentThread().getName() + " ---Blacklist Flip");
                e.printStackTrace();
            } catch (IOException e) {
                //System.out.println("Thread: " + Thread.currentThread().getName());
                catchflip = false;
                setBlacklist(true);
                System.out.println("Thread: " + Thread.currentThread().getName() + " ---Blacklist Flip");
                e.printStackTrace();
            }
            if (catchflip) System.out.println("Thread: " + Thread.currentThread().getName() + " Created a Socket Successfully...");
     
        }
        public void stopConnection() {
            try {
                in.close();
                out.close();
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Thread: " + Thread.currentThread().getName() + " Socket Closed");
        }
    }

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    That looks like too long a list of IP addresses for testing
    Is that the minimum list required for testing and finding the problem?
    The shorter the better for testing.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    So that's a list I just pulled down from the servers for one torrent. Peers will connect and disconnect form the pool as time goes on so not all of them will work forever. I think though that torrent has a few active seeders so the list will work hopefully for a few days. You can just remove form the list as you wish and everything will still work. Just don't remove all the seeds that connect.

    If you edit the PeerManager class where roolpeer() is being called you can specify the peers to connect too and not have the program chose randomly. The connected and notconnect ArrayLists hold as an object the index of the peer from the peerlist. So that wont always match up with their indexes.

    If you need the list updated just ask and I can re-pull it. I would give you you class that dose that but I can't be bothered to edit it so it works with that Main class.
    Last edited by Blick; August 24th, 2019 at 10:21 AM.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    What I am looking for in a short list of IP addresses to test with. Something that shows the problem and does not need to be changed while testing.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Erm Google? I have no idea where to get a list of testing IPs. I have just been using the live ones.

    This is the first time I have programmed any network stuff.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    where to get a list of testing IPs
    Write one that uses 127.0.0.1 with different ports. Have a local server that runs those sockets for testing.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Just so the socket connects? I not really in the mood to write a server for the whole Bittorrent protocol right now. I can add to it later. Just want to get this while loop fixed so I can move on.

    I can get it done tomorrow. I have been messing around with the GUI all day and I'm tired.

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    ok, whenever you can do it. I'm in no hurry.

    For testing there should be a reliable model that shows the problem when executed. When the input data can change randomly, it makes it hard to debug.

    I'm not sure what the problem is. I don't see any comments in the posted output saying where the problem is.
    I would expect to see something like:
    >>>********* Here the output should be .....whatever <<<<<<
    If you don't understand my answer, don't ignore it, ask a question.

  14. #14
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    I just finished a quick Server and Client program.

    Here is the server:
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.UnknownHostException;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.ArrayList;
     
    public class Main {
     
        public static void main(String[] args) {
     
            //----------------- Simple Server -----------------
     
     
            //Set IP address here --------------------
            InetAddress LocalIP = null;
            try {
                LocalIP = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
     
            //Set Port list here -------------------
            int[] ports = {4000,4001,4002,4003};
     
            // Array of server sockets
            ArrayList<ServerSocketChannel> serverSockets = new ArrayList<ServerSocketChannel>();
     
            //Create Sockets for each port number
            for (int i = 0; i < ports.length; i++){
                try {
                    serverSockets.add(ServerSocketChannel.open());
                    serverSockets.get(i).configureBlocking(false);
                    serverSockets.get(i).socket().bind(new InetSocketAddress(LocalIP, ports[i]));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
     
            System.out.println("Server is UP!");
     
            //Accept Connections
            while (true){
                for (int i = 0; i < serverSockets.size(); i ++){
                    SocketChannel clientSocket = null;
                    try {
                        clientSocket = serverSockets.get(i).accept();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (clientSocket != null){
                        System.out.println("Socket Connection Accepted -- on Port: " + ports[i]);
                    }
     
                }
            }
        }
    }

    Just encase you wanted it this is a simple client I was using to test the server:
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
     
    public class Main {
     
        public static void main(String[] args) {
     
            //----------------- Simple Client -----------------
     
            //Set IP address here --------------------
            InetAddress LocalIP = null;
            try {
                LocalIP = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
     
            //Set Port here
            int port = 4001;
     
            boolean flip = true;
     
            //Connect ----------------------------
            try {
                Socket socket = new Socket(LocalIP, port);
            } catch (UnknownHostException e) {
                flip = false;
                System.out.println("There was a problem on port" + port + "...");
                e.printStackTrace();
            } catch (IOException e) {
                flip = false;
                System.out.println("There was a problem on port" + port + "...");
                e.printStackTrace();
            }
     
            if (flip) System.out.println("Client Connected on Port: " + port);
     
     
        }
    }


    Quote Originally Posted by Norm View Post
    I would expect to see something like:
    >>>********* Here the output should be .....whatever <<<<<<
    Add this to line 85 of the PeerManager class:
    /*
                    ------>>>>> Here is the Problem with the code <<<<<------
                    Bellow is a for loop used of blacklisting peers that do not connect.
                    Inside of the PeerConnect Class, a Flag is set true if a Peer is to be blacklisted
                    The below for loop is checking for that flag
     
                    The problem is once the PeerConnect thread start to throw errors the while loop
                    this comment is inside of stops looping. This can be seen in the output as
                    the above "Loop Run Marker-----" System.out Stops Printing
     
                    This means that once PeerConnect threads start to get their blacklist flags set
                    This main while loop is no longer running and the bellow blacklist for loop never
                    runs again.
     
                    I don't know why this while loop stops running but it seems to stop as the
                    PeerConnect errors begin to throw.
     
                     */

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    I just finished a quick Server and Client program.
    Thanks for the code samples.

    Do those programs when executed show the problem?
    Do you have some print out from when those programs are executed that shows the problem?
    Please post the print out with some comments where the output shows the problem.

    My request for comment was for the output:
    comments in the posted output saying where the problem is.
    I would expect to see something like:
    >>>********* Here the output should be .....whatever <<<<<<
    Also the code needs comments describing what it is trying to do and how it is going to do it.
    If you don't understand my answer, don't ignore it, ask a question.

  16. #16
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Quote Originally Posted by Norm View Post
    Do those programs when executed show the problem?
    The program right now is not doing anything but trying to open a socket in each thread. Other than that its not sending any information to the server.

    Let me be sure of everything you want:

    - The classes but with more comments in them describing how they work
    - The simple Server program for testing
    - A commented version of the output describing the problem

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    Yes, that sounds about right. There needs to be a good test environment that will consistently show the problem when executed.
    Given that, it should be possible to track down the problem.
    Comments will help in understanding what the code is trying to do and can be used to see if the code is actually doing what the comments say it is supposed to do.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #18
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Alright lets try this one more time.

    Main:
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
     
    public class Main {
     
        public static void main(String[] args) {
            //All this program is attempting to do is:
            //Create sockets and connect to a list of IP:Port combinations in separate threads
            //It dose not send or receive any other data
     
            //The PeerManager thread is designed to manage arrays of PeerConnect threads
            //PeerConnect Threads attempt to open a socket to a randomly chosen IP:Port from the given List
     
            //Just variables being passed ---
            //Not part of the logic but needed for the PeerManger Constructor
            int pid = 0;
            int Noofpieces = 91;
            String infohash = "5805199A9917AEFA79412656663DCEF23557229F";
     
            //Set IP address here --------------------
            InetAddress LocalIP = null;
            try {
                //Get the Local IP
                LocalIP = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
     
            //Add List of Ports here --------------------
            int[] ports = {4000,4001,4002,4003,4004,4005,4006};
     
            //Set local IP to string for passing to the peerlist ArrayList
            String IP = LocalIP.getHostAddress();
     
            //Peerlist holding concatenated IP and Port numbers - separated by a ":" character
            ArrayList<String> peerlist = new ArrayList<String>() {};
            //add all port numbers to ArrayList
            for (int i = 0; i < ports.length; i ++){
                peerlist.add(IP + ":" + ports[i]);
                System.out.println("Port: " + peerlist.get(i) + " -- added");
            }
     
            //Creating a a PeerManager Thread
            PeerManager peermanager = new PeerManager(peerlist, Noofpieces, infohash, pid);
            //Starting the Thread
            peermanager.start();
        }
    }

    PeerManager:
    import java.util.ArrayList;
    import java.util.Random;
     
    public class PeerManager extends Thread {
     
        //It is the PeerManagers job to manage PeerConnect Threads
        //Right now it controls the number of PeerConnections to create
        //it then Updates the connected and not connected Arraylist to keep track of connected peers
        //Peer are chosen at random by the rool() method
        //It attempts to blacklist peers that fail to connect
     
        //The problem is this threads main while loop seems to stop running once peerconnect threads throw errors
     
        //The bellow variables are currently not in use
        int ID;
        ArrayList<Long> downspeed = new ArrayList<Long>();
        long pieceno = 0;
        //list of black to be downloded - not implemented yet
        boolean[] donelist;
        String infohash;
     
     
        //Array of peerconnect threads
        //Peer connect threads handel the actual socket connection
        //This is so connections can run in parallel
        ArrayList<PeerConnect> peerconnection = new ArrayList<PeerConnect>();
     
        //The peerlist holds all of the IP:Port numbers added
        ArrayList<String> peerlist = new ArrayList<String>();
        //Connected holds as an object the index of connected PeerConnect threads
        //This int object is the index of that peer in the peerlist
        ArrayList<Integer> connected = new ArrayList<Integer>();
        //holds as an object the index of not connected PeerConnect threads
        ArrayList<Integer> notconnected = new ArrayList<Integer>();
        //holds as an object the index of PeerConnect threads that failed to connect
        ArrayList<Integer> blacklist = new ArrayList<Integer>();
     
        //flag for a static variable
        //Peer Connect has a static list of block to download
        //This is initialized but not implemented
        boolean flipblocklist = false;
     
        //the constructor bellow is not doing much
        //Just passing variables
        public PeerManager(ArrayList<String> array, int nopieces, String hash, int pid){
     
     
            //Passing the IP:Port list from Main
            peerlist = (ArrayList<String>)array.clone();
     
            //add all peers to the notconnected list
            for (int i = 0; i < peerlist.size(); i++){
                notconnected.add(i);
            }
     
            ID = pid;
            setPieceno(nopieces);
            infohash = hash;
     
        }
     
     
        @Override
        public void run() {
            //Main thread loop
            //-----------------This while loop has the problem-----------
            while (true){
     
                //creates a new peer thread if there is less than 20 threads and there are still peers left to connect too
                if (connected.size() < 20 && notconnected.size() > 0){
                    int last;
                    peerconnection.add(new PeerConnect());
     
                    //index of current object in peerconnection -- the thread we just created
                    last = peerconnection.size() - 1;
     
                    //select random peer and update lists
                    int newpeer = roolpeer();
                    //pass that peer to new thread
                    peerconnection.get(last).setPeerin(peerlist.get(newpeer));
                    //updating the connected and notconnected lists
                    connected.add(newpeer);
                    int remove;
                    remove = notconnected.indexOf(newpeer);
                    notconnected.remove(remove);
     
                    //setting thread name
                    //Threads are named by peerlist index - not creation order
                    //A threads name is the index of that peer in the peerlist ArrayList
                    peerconnection.get(last).setName(Integer.toString(newpeer));
                    peerconnection.get(last).setNamein(Integer.toString(newpeer));
                    peerconnection.get(last).setInfohash(infohash);
     
                    //starting the new thread
                    peerconnection.get(last).start();
     
                    //setting of static variable during the first peerconnect object creation only
                    //Not in use
                    if (!flipblocklist){
     
                        for (int i = 0; i < getPieceno(); i ++){
                            peerconnection.get(0).setBlocklist(i);
                        }
                        flipblocklist = true;
                    }
     
                    //--------end of peerconnection creation
     
                    //A marker used to check the main while loop is still running
                    System.out.println("loop Run Marker-------------------------loop Run Marker");
     
                    /*
                    ------>>>>> Here is the Problem with the code <<<<<------
                    Bellow is a for loop used of blacklisting peers that do not connect.
                    Inside of the PeerConnect Class, a Flag is set true if a Peer is to be blacklisted
                    The below for loop is checking for that flag
     
                    The problem is once the PeerConnect thread start to throw errors the while loop
                    this comment is inside of stops looping. This can be seen in the output as
                    the above "----Loop Run Marker----" System.out Stops Printing
     
                    This means that once PeerConnect threads start to get their blacklist flags set
                    This main while loop is no longer running and the bellow blacklist for loop never
                    runs again.
     
                    I don't know why this while loop stops running but it seems to stop as the
                    PeerConnect errors begin to throw.
     
                    To test this try connecting to closed ports and open ports at the same time
     
                    */
                    //----------------------------------------------------
     
     
                    //This for bellow loop is checking to see if a peerconnect thread has had its blacklist flag set
                    //peers with flags set true will be blaclisted
                    //Peers are blacklisted because they failed to connect
                    //------blacklist bad sockets----------------------
                    for (int i = 0; i < peerconnection.size(); i++){
                        //System.out.println("Thread: " + i + " is " + peerconnection.get(i).getBlacklist());
                        //check flag
                        if (peerconnection.get(i).getBlacklist() == true){
                            // This block of code never seems to run
                            System.out.println("------------blackloop running");
                            String holdname = peerconnection.get(i).getPeerin();
                            //Removes peer thread and updates lists
                            peerconnection.remove(i);
                            connected.remove(Integer.valueOf(holdname));
                            blacklist.add(Integer.valueOf(holdname));
                            System.out.println("Peer: " + holdname + " was Blacklisted");
                        }
                    }
                }
     
     
            }
     
     
     
        }
        public long getPieceno() {
            return pieceno;
        }
     
        public void setPieceno(long pieceno) {
            this.pieceno = pieceno;
            int temp = (int) this.pieceno;
            donelist = new boolean[temp];
     
            for (int i = 0; i < donelist.length; i ++){
                donelist[i] = false;
            }
        }
        //Select a random peer to connect too
        public int roolpeer(){
            //Picks a random peer
            int ID;
     
            //select from notconnected peers
            Random rand = new Random();
            int n = rand.nextInt(notconnected.size());
     
            ID = notconnected.get(n);
     
            return ID;
        }
    }

    PeerConnect:
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
     
    public class PeerConnect extends Thread {
        //All this thread dose is split the IP:Port string into a separate IP and Port variable
        //It then tries to open a socket to that port
     
        //Ip Port Variables
        String namein;
        String peerin;
        String IP;
        int port;
     
        //not implemented yet
        String infohash;
     
        //Flag is set true if the socket fails to connect
        //The PeerManager checks for this flag so it can blacklist the peer
        volatile boolean Blacklist = false;
     
        //-------Socket Variables -----------
        Socket clientSocket;
        DataOutputStream out;
        DataInputStream in;
        //--------------------------------
     
        //initialized but not in use
        static volatile ArrayList<Integer> blocklist = new ArrayList<Integer>();
     
        @Override
        public void run() {
            //Thread Creation Messages
            System.out.println("Thread ID: Peer " + Thread.currentThread().getName() + " -- Created");
            System.out.println("Peer Info: " + getPeerin());
     
            //split the IP:Port string
            peersplit();
     
            //Attempt to open socket
            startConnection();
            //stopConnection();
        }
     
        public String getNamein() {
            return namein;
        }
     
        public void setNamein(String namein) {
            this.namein = namein;
        }
     
        public String getPeerin() {
            return peerin;
        }
     
        public void setPeerin(String peerin) {
            this.peerin = peerin;
        }
     
        public synchronized static int getBlocklist(int object) {
            int index = blocklist.indexOf(object);
            int output = blocklist.get(index);
     
            return output;
        }
        public synchronized boolean getBlacklist() {
            return Blacklist;
        }
     
        public synchronized void setBlacklist(boolean blacklist) {
            Blacklist = blacklist;
        }
     
        public static void removeBlocklist(int object){
            int index = blocklist.indexOf(object);
            blocklist.remove(index);
        }
     
        public static void setBlocklist(int item) {
            blocklist.add(item);
        }
     
        public String getInfohash() {
            return infohash;
        }
     
        public void setInfohash(String infohash) {
            this.infohash = infohash;
        }
     
     
        //Method to split the IP:Port string
        public void peersplit(){
            String hold = peerin;
            int index = hold.indexOf(":");
            IP = hold.substring(0, index);
            port = Integer.valueOf(hold.substring(index + 1));
     
        }
     
        //Attempt to open socket
        public void startConnection() {
     
            // a flag for debugging messages
            boolean catchflip = true;
     
            //Try to create socket and in - Out
            try {
                clientSocket = new Socket(IP, port);
                out = new DataOutputStream(clientSocket.getOutputStream());
                in = new DataInputStream(clientSocket.getInputStream());
                stopConnection();
            } catch (UnknownHostException e) {
                //Set false for bellow dubug message
                catchflip = false;
                //Set blacklist flag if connection fails
                setBlacklist(true);
                System.out.println("Thread: " + Thread.currentThread().getName() + " ---Blacklist Flip");
                e.printStackTrace();
            } catch (IOException e) {
                //Set false for bellow dubug message
                catchflip = false;
                //Set blacklist flag if connection fails
                setBlacklist(true);
                System.out.println("Thread: " + Thread.currentThread().getName() + " ---Blacklist Flip");
                e.printStackTrace();
            }
            //Print if socket connects
            if (catchflip) System.out.println("Thread: " + Thread.currentThread().getName() + " Created a Socket Successfully...");
     
        }
     
        //Close a socket and clean up
        public void stopConnection() {
            try {
                in.close();
                out.close();
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Thread: " + Thread.currentThread().getName() + " Socket Closed");
        }
    }

    Simple Server Program:
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.UnknownHostException;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.ArrayList;
     
    public class Main {
     
        public static void main(String[] args) {
     
            //----------------- Simple Server -----------------
     
            //This server will print out the port number of accepted sockets
     
     
            //Set IP address here --------------------
            InetAddress LocalIP = null;
            try {
                LocalIP = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
     
            //Set Port list here -------------------
            int[] ports = {4000,4001,4002,4003};
     
            // Array of server sockets
            ArrayList<ServerSocketChannel> serverSockets = new ArrayList<ServerSocketChannel>();
     
            //Create Sockets for each port number
            for (int i = 0; i < ports.length; i++){
                try {
                    serverSockets.add(ServerSocketChannel.open());
                    serverSockets.get(i).configureBlocking(false);
                    serverSockets.get(i).socket().bind(new InetSocketAddress(LocalIP, ports[i]));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
     
            System.out.println("Server is UP!");
     
            //Accept Connection
            while (true){
                for (int i = 0; i < serverSockets.size(); i ++){
                    SocketChannel clientSocket = null;
                    try {
                        clientSocket = serverSockets.get(i).accept();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (clientSocket != null){
                        System.out.println("Socket Connection Accepted -- on Port: " + ports[i]);
                    }
     
                }
            }
        }
    }

    Commented Output:
    ***User Comments surrounded with *** ***
     
    ***Here is the output from one test***
    ***I'm trying to connect to 7 ports***
    ***Ports 4000,4001,4002,4003 are open on the simple server***
    ***Ports 4004,4005,4006 are not open***
    ***This is to show how the threads deal with a bad fail connection during socket creation***
     
    ***Ports added to the peerlist***
    Port: 10.50.20.33:4000 -- added
    Port: 10.50.20.33:4001 -- added
    Port: 10.50.20.33:4002 -- added
    Port: 10.50.20.33:4003 -- added
    Port: 10.50.20.33:4004 -- added  ***Not Open on Server"***
    Port: 10.50.20.33:4005 -- added  ***Not Open on Server"***
    Port: 10.50.20.33:4006 -- added  ***Not Open on Server"***
     
    loop Run Marker-------------------------loop Run Marker  ***Loop Marker shows the PeerManager's main while loop is still running***
     
    Thread ID: Peer 0 -- Created        ***Threads being created*** ***Thread ID is the Index of the port number***
    Peer Info: 10.50.20.33:4000
    loop Run Marker-------------------------loop Run Marker
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 1 -- Created
    Peer Info: 10.50.20.33:4001
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 4 -- Created
    Peer Info: 10.50.20.33:4004
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 2 -- Created
    Peer Info: 10.50.20.33:4002
    loop Run Marker-------------------------loop Run Marker
    loop Run Marker-------------------------loop Run Marker ***This is the lst time that the loop marker is seen to print***
                                                            ***PeerManger's main while loop is no longer running***
     
    Thread ID: Peer 5 -- Created
    Peer Info: 10.50.20.33:4005
    Thread ID: Peer 6 -- Created
    Peer Info: 10.50.20.33:4006
    Thread ID: Peer 3 -- Created
    Peer Info: 10.50.20.33:4003
     
    ***All of the open server sockets connect as expected***
    Thread: 0 Socket Closed
    Thread: 0 Created a Socket Successfully...
    Thread: 3 Socket Closed
    Thread: 3 Created a Socket Successfully...
    Thread: 2 Socket Closed
    Thread: 2 Created a Socket Successfully...
    Thread: 1 Socket Closed
    Thread: 1 Created a Socket Successfully...
     
    Thread: 5 ---Blacklist Flip  ***The first failed connection. This shows that this threads Blacklist Flag is now set true***
    Thread: 4 ---Blacklist Flip
    java.net.ConnectException: Connection refused: connect     ***connection errors on the expected port***
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:112)
    	at PeerConnect.run(PeerConnect.java:43)
    java.net.ConnectException: Connection refused: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:112)
    	at PeerConnect.run(PeerConnect.java:43)
    Thread: 6 ---Blacklist Flip
    java.net.ConnectException: Connection refused: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:589)
    	at java.net.Socket.connect(Socket.java:538)
    	at java.net.Socket.<init>(Socket.java:434)
    	at java.net.Socket.<init>(Socket.java:211)
    	at PeerConnect.startConnection(PeerConnect.java:112)
    	at PeerConnect.run(PeerConnect.java:43)
     
    ***We still have not seen another --LoopMarker-- message by this point. The PeerManager's main while loop is defiantly not running***
    ***The while loop is set as "while(true)" so it should run indefinitely***
    ***As some of the threads blacklist flag was set. We should have also seen massages showing that those ports have been blacklisted***
    ***Obviously we don't see this because the main while loop has stopped***
     
    ***Just to confirm bellow is the server output showing the correct connections***
     
    Server is UP!
    Socket Connection Accepted -- on Port: 4000
    Socket Connection Accepted -- on Port: 4001
    Socket Connection Accepted -- on Port: 4002
    Socket Connection Accepted -- on Port: 4003

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    The program has a bad loop. Wen I compile and execute the code, the CPU usage goes up to over 60%???
    My output before I did an "end task":
    Running: java.exe -client PeerTesting2

    Server created Socket port=4000
    Server created Socket port=4001
    Server created Socket port=4002
    Server created Socket port=4003
    Server is UP!
    Port: 192.168.56.1:4000 -- added
    Port: 192.168.56.1:4001 -- added
    Port: 192.168.56.1:4002 -- added
    Port: 192.168.56.1:4003 -- added
    Port: 192.168.56.1:4004 -- added
    Port: 192.168.56.1:4005 -- added
    Port: 192.168.56.1:4006 -- added
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 1 -- Created
    loop Run Marker-------------------------loop Run Marker
    Thread ID: Peer 0 -- Created
    loop Run Marker-------------------------loop Run Marker
    Peer Info: 192.168.56.1:4001
    Peer Info: 192.168.56.1:4000
    loop Run Marker-------------------------loop Run Marker
    loop Run Marker-------------------------loop Run Marker
    loop Run Marker-------------------------loop Run Marker
    loop Run Marker-------------------------loop Run Marker
    Thread: 1 Socket Closed
    Thread: 1 Created a Socket Successfully... port=4001
    Thread: 0 Socket Closed
    Thread: 0 Created a Socket Successfully... port=4000
    Socket Connection Accepted -- on Port: 4000
    Socket Connection Accepted -- on Port: 4001
    Thread ID: Peer 6 -- Created
    Peer Info: 192.168.56.1:4006
    Thread ID: Peer 5 -- Created
    Peer Info: 192.168.56.1:4005
    Thread ID: Peer 2 -- Created
    Peer Info: 192.168.56.1:4002
    Thread: 2 Socket Closed
    Thread: 2 Created a Socket Successfully... port=4002
    Socket Connection Accepted -- on Port: 4002
    Thread ID: Peer 3 -- Created
    Peer Info: 192.168.56.1:4003
    Thread: 3 Socket Closed
    Thread: 3 Created a Socket Successfully... port=4003
    Thread ID: Peer 4 -- Created
    Peer Info: 192.168.56.1:4004
    Socket Connection Accepted -- on Port: 4003
    setBL true for port=4005
    Thread: 5 1---Blacklist Flip port=4005
    java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Un known Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress( Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at PeerTesting2$PeerConnect.startConnection(PeerTesti ng2.java:546)
    at PeerTesting2$PeerConnect.run(PeerTesting2.java:476 )
    setBL true for port=4004
    Thread: 4 1---Blacklist Flip port=4004
    java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Un known Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress( Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at PeerTesting2$PeerConnect.startConnection(PeerTesti ng2.java:546)
    at PeerTesting2$PeerConnect.run(PeerTesting2.java:476 )
    setBL true for port=4006
    Thread: 6 1---Blacklist Flip port=4006
    java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Un known Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress( Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at PeerTesting2$PeerConnect.startConnection(PeerTesti ng2.java:546)
    at PeerTesting2$PeerConnect.run(PeerTesting2.java:476 )
    Exiting main

    0 error(s)


    There is a forever/hot loop in the server:
            //Accept Connection
            while (true){                          //<<<<<<< HOT LOOP ????
    That should be changed to use a Selector
    If you don't understand my answer, don't ignore it, ask a question.

  20. The Following User Says Thank You to Norm For This Useful Post:

    Blick (August 25th, 2019)

  21. #20
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Yeah I have no idea what's wrong with it. Let me know if you manager to find the problem.

    Thanks for helping out BTW

  22. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    The code needs some more println statements for debugging. Print out the values of variables and lists so you can see what is happening.
    Add a toString method to the PeerConnection class so that its print outs will show you what the instance of the class contains.
    If you don't understand my answer, don't ignore it, ask a question.

  23. #22
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Quote Originally Posted by Norm View Post
    The code needs some more println statements for debugging. Print out the values of variables and lists so you can see what is happening.
    Add a toString method to the PeerConnection class so that its print outs will show you what the instance of the class contains.
    I don't understand what you want to print out. Do you want to print out the IP, Port and Socket variables?

    Did you make any progress with the broken while loop?

  24. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    don't understand what you want to print out
    You need to see the contents of the variables and lists to see where the problems are. For example what is in peerconnection?

    the broken while loop
    What was wrong with the printout I posted?
    Why do you think it is broken? What variables value's control when the loop executes and how. Print out the values of the variables that controls the execution of the loop.
    If you don't understand my answer, don't ignore it, ask a question.

  25. #24
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Threads and Sockets

    Don't worry I fixed it myself:

    "C:\Program Files\Java\jdk1.8.0_211\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.3\lib\idea_rt.jar=55502:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_211\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\rt.jar;C:\Users\Ben\IdeaProjects\tempmain rabbit\out\production\tempmain rabbit" Main
    Port: 10.50.20.33:4000 -- added
    Port: 10.50.20.33:4001 -- added
    Port: 10.50.20.33:4002 -- added
    Port: 10.50.20.33:4003 -- added
    Port: 10.50.20.33:4004 -- added
    Port: 10.50.20.33:4005 -- added
    Port: 10.50.20.33:4006 -- added
    Thread ID: Peer 6 -- Created
    Peer Info: 10.50.20.33:4006
    Thread ID: Peer 2 -- Created
    Peer Info: 10.50.20.33:4002
    Thread ID: Peer 5 -- Created
    Peer Info: 10.50.20.33:4005
    Thread ID: Peer 3 -- Created
    Peer Info: 10.50.20.33:4003
    Thread ID: Peer 4 -- Created
    Peer Info: 10.50.20.33:4004
    Thread ID: Peer 0 -- Created
    Peer Info: 10.50.20.33:4000
    Thread ID: Peer 1 -- Created
    Peer Info: 10.50.20.33:4001
    Peer: 1 was Blacklisted ---------
    Peer: 6 was Blacklisted ---------
    Peer: 5 was Blacklisted ---------
    Peer: 2 was Blacklisted ---------
    Peer: 4 was Blacklisted ---------
    Peer: 3 was Blacklisted ---------
    Peer: 0 was Blacklisted ---------

  26. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,383
    Thanks
    53
    Thanked 2,398 Times in 2,351 Posts

    Default Re: Threads and Sockets

    Glad you figured it out.
    The print out shows that all IPs were black listed. Is that what is expected? Why aren't there any IPs that are not blacklisted?

    A good test case would have some IPs that are not blacklisted. Is your testing scheme working properly?
    If you don't understand my answer, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. problem using Sockets
    By Jedi khan in forum What's Wrong With My Code?
    Replies: 13
    Last Post: August 2nd, 2013, 05:44 PM
  2. Sockets in JApplet
    By shrey.haria in forum Java Networking
    Replies: 4
    Last Post: September 5th, 2011, 09:45 AM
  3. [SOLVED] Problems with Sockets
    By Samthere in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 21st, 2011, 06:02 AM
  4. Threads, Sockets & jFrame
    By Rakshasas in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 11th, 2011, 06:28 PM
  5. Java sockets help
    By ma05k1 in forum Java Theory & Questions
    Replies: 1
    Last Post: March 27th, 2010, 05:52 AM