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.

Results 1 to 8 of 8

Thread: Java - Node Prime Solver

  1. #1
    Junior Member
    Join Date
    Dec 2017
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Java - Node Prime Solver

    Hey. I made a software using Sockets to create a server, and then use clients ( bots ), which do the math and report back to the server. There's a few problems going on in my code. For some reason, the server is using a port not specified by the code. (???), and the handshake isn't working.

    Launcher
    import java.util.Scanner;
     
    import static kit.BuildInfo.*;
     
    public class Launcher {
     
        public static void main(String[] args) {
            System.out.println("CrowdSource Data Miner - Prime Number Finder\nBy Ethan Manzi\nVersion " + version + " - " + build + "\n\n");
            System.out.println("Please select what software you would like to run");
            System.out.println("[S]erver\n[C]lient\n[B]oth");
            Scanner s = new Scanner(System.in);
            String option = s.nextLine();
            if (option.equalsIgnoreCase("s")) {
                System.out.println("Starting server.....");
                new server.main();
            } else if (option.equalsIgnoreCase("c")) {
                System.out.println("Starting Miner.....");
                new client.main();
            } else if (option.equalsIgnoreCase("b")) {
                System.out.println("Attemping to run server and miner.....");
            }
        }
    }
     
    /*
    System.out.print("Server Address: ");
            Scanner s = new Scanner(System.in);
            String svr = s.nextLine();
            ipAddress = svr;
     */

    server.main
    package server;
     
    import sun.misc.Launcher;
     
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
    import static kit.BuildInfo.*;
     
    public class main {
        public static int clients = 0;
        static DataInputStream input;
        static PrintStream output;
        static ServerSocket MyService;
        static String idenity = "";
     
        public static int n = 1;
     
        public main() {
            Scanner s = new Scanner(System.in);
            System.out.print("Server Identifier: ");
            idenity = s.nextLine();
            System.out.println("Running server at localhost:" + port);
            capter();
        }
     
        private void capter() {
     
     
     
            try { MyService = new ServerSocket(61875); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally {
                System.out.println("Server Open!");
                System.out.println(MyService.getLocalPort());
                if (MyService.isClosed()) {
                    System.out.println("NOT OPEN");
                }
                if (MyService.isBound()) {
                    System.out.println("Bound");
                }
            }
     
            while (true) {
                // accept connections from clients
                try {
                    Socket clientSocket = MyService.accept();
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                System.out.println("New Connection");
                                Socket fwd = clientSocket;
                                client(fwd);
                            } catch (Exception e) {
     
                            } finally {
     
                            }
                        }
                    }).start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
     
        static Writer out;
        static Socket m;
     
        int client(Socket s) {
            m=s;
            // get communication
            try {
                new File("Primes.txt").delete();
                // new BufferedWriter(new FileWriter("Primes.txt",true));
                input = new DataInputStream(s.getInputStream());
                output = new PrintStream(s.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("\nError in getting communication");
                System.exit(1);
            } finally {
     
            }
     
            //preform handshake
            try {
                output.println("listening");
                String intent = input.readLine();
                if (intent.equalsIgnoreCase("ping")) {
                    output.println(clients);
                    output.println(idenity);
                    output.println(build);
                    output.println("exit");
                    String reply = input.readLine();
                    disconnect();
                    return 0;
                } else if (intent.equalsIgnoreCase("connect")) {
                    String id = input.readLine();
                    if (id.equalsIgnoreCase(identifer)) {
                        output.println("100");
                    } else {
                        output.println("662");
                        disconnect();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("\nError in getting handshake");
                System.exit(1);
            }
     
     
            //begin
            clients++;
            while (true) {
                try {
                    String sta = input.readLine();
                    if (sta.equalsIgnoreCase("ready")) {
                        int lock = n; n++;
                        output.println(lock);
                        String reply = input.readLine();
                        if (reply.equalsIgnoreCase("yes")) {
                            out = new BufferedWriter(new FileWriter("Primes.txt",true));
                            out.append("\n" + lock);
                            out.close();
                        }
                    }
                } catch (Exception e) {
     
                } finally {
     
                }
            }
        }
     
     
        private void disconnect() {
            try {
                input.close();
                output.close();
                m.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            } finally {
                System.out.println("Client Disconnected");
                clients--;
            }
        }
    }
     
    /*
     
        Codes:
            100 - Accepted
            662 - Invalid Version
     
     */

    client.main
    package client;
     
    import jdk.nashorn.internal.runtime.ECMAException;
     
    import java.io.DataInputStream;
    import java.io.PrintStream;
    import java.net.Socket;
    import java.util.Scanner;
    import static kit.BuildInfo.*;
     
    public class main {
        public final String ip;
        public final int Threads;
     
        public int inp = port;
     
        DataInputStream input;
        PrintStream output;
        Socket MyClient;
     
        int ct = 0;
     
        public main() {
            Scanner s = new Scanner(System.in);
            System.out.print("Server: ");
            ip = s.nextLine();
            System.out.print("Threads: ");
            Threads = Integer.parseInt(s.nextLine());
            System.out.print("port(" + port + ") Enter [0] for default: ");
            int p = s.nextInt();
            if (p==0) {} else {
                inp=p;
            }
     
            //ping the server
            System.out.println("Pining server: " + ip + ":" + inp);
            try {
                MyClient = new Socket(ip, inp);
                System.out.println("Status: " + MyClient.isConnected());
                input = new DataInputStream(MyClient.getInputStream());
                output = new PrintStream(MyClient.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            } finally {
                try {
                    System.out.println("Establishing Handshake....");
                    String responce;
                    responce = input.readLine();
                    if (responce.equalsIgnoreCase("listening")) {
                        System.out.println("Sending command....");
                        output.println("ping");
                        System.out.println("Getting Data....");
                        String clientCount = input.readLine();
                        String id = input.readLine();
                        String build = input.readLine();
                        String status = input.readLine();
                        output.println("OK");
                        try {
                            output.close();
                            input.close();
                            MyClient.close();
                            System.out.println("Disconnected");
                        } catch (Exception e) {System.out.println("System already disconnected!");}
                    } else {
                        System.out.println("Critical Error in Handshake!");
                        System.exit(1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
     
            for (int i=0; i<Threads; i++) {
                Thread t = new Thread(new Runnable() {
                    public void run() {
                        int lock=ct;ct++;
                        connect(lock);
                    }
                });
     
                t.start();
            }
        }
     
        private void connect(int n) {
            System.out.println("Thread " + n + " - online");
            //handshake
            try {
                MyClient = new Socket(ip, inp);
                System.out.println("Establishing Handshake....");
                String responce;
                responce = input.readLine();
                if (responce.equalsIgnoreCase("listening")) {
                    output.println("connect");
                    output.println(identifer);
                    String st = input.readLine();
                    System.out.println("Handshake Reply: " + st);
                } else {
                    System.out.println("Critical Error in Handshake!");
                    System.exit(1);
                }
            } catch(Exception e) {
     
            }
     
            while (true) {
                try {
                    output.println("ready");
                    int test = Integer.parseInt(input.readLine());
     
                    boolean prime = true;
     
                    System.out.println("Checking number");
                    for (int i=2; i<test-1; i++)
                    {
                        if (test % i == 0) {
                            prime=false;
                        }
                    }
     
                    if (prime) {
                        output.println("yes");
                    } else {
                        output.println("yes");
                    }
     
                } catch (Exception e) {
                    e.printStackTrace();
                    if (MyClient.isConnected()) {
                        System.out.println("Still connected");
                    } else {
                        System.out.println("Lost Connection!");
                        System.exit(1);
                    }
                    System.exit(1);
                }
            }
        }
    }

    kit.BuildInfo
    package kit;
     
    public class BuildInfo {
        public static final String version = "Alpha 1";
        public static final int build = 17;
        public static final String identifer = "thisisliketotallymysecondtrydoingthis";
        public static final int port = 2121;
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,404
    Thanks
    53
    Thanked 2,399 Times in 2,352 Posts

    Default Re: Java - Node Prime Solver

    Can you copy the debug output you get when executing your code and post it here so we can see what you are talking about?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Dec 2017
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java - Node Prime Solver

    Client says
    CrowdSource Data Miner - Prime Number Finder
    By Ethan Manzi
    Version Alpha 1 - 17
     
     
    Please select what software you would like to run
    [S]erver
    [C]lient
    [B]oth
    c
    Starting Miner.....
    Server: localhost
    Threads: 1
    port(2121) Enter [0] for default: 61875
    Pining server: localhost:61875
    Status: true
    Establishing Handshake....
    Sending command....
    Getting Data....
    Disconnected
    Thread 0 - online
    Establishing Handshake....
    Still connected
    java.net.SocketException: Socket closed
    	at java.net.SocketInputStream.socketRead0(Native Method)
    	at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    	at java.net.SocketInputStream.read(SocketInputStream.java:171)
    	at java.net.SocketInputStream.read(SocketInputStream.java:141)
    	at java.net.SocketInputStream.read(SocketInputStream.java:224)
    	at java.io.DataInputStream.readLine(DataInputStream.java:513)
    	at client.main.connect(main.java:110)
    	at client.main.access$000(main.java:11)
    	at client.main$1.run(main.java:78)
    	at java.lang.Thread.run(Thread.java:748)
     
    Process finished with exit code 1
    and the sever says
    Ethans-MacBook-Pro:NBPG coderboy14$ java -jar /Users/coderboy14/IdeaProjects/CrowdSource-PrimeFinder/out/artifacts/CrowdSource_PrimeFinder_jar/CrowdSource-PrimeFinder.jar
    CrowdSource Data Miner - Prime Number Finder
    By Ethan Manzi
    Version Alpha 1 - 17
     
     
    Please select what software you would like to run
    [S]erver
    [C]lient
    [B]oth
    S
    Starting server.....
    Server Identifier: ethan
    Running server at localhost:2121
    Server Open!
    61875
    Bound
    New Connection
    Client Disconnected
    New Connection
    java.net.SocketException: Connection reset
    	at java.net.SocketInputStream.read(SocketInputStream.java:210)
    	at java.net.SocketInputStream.read(SocketInputStream.java:141)
    	at java.net.SocketInputStream.read(SocketInputStream.java:224)
    	at java.io.DataInputStream.readLine(DataInputStream.java:513)
    	at server.main.client(main.java:88)
    	at server.main$1.run(main.java:52)
    	at java.lang.Thread.run(Thread.java:748)
     
    Error in getting handshake

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,404
    Thanks
    53
    Thanked 2,399 Times in 2,352 Posts

    Default Re: Java - Node Prime Solver

    Note: using the name main for a class makes the code hard to read and understand. Standard java class names start with uppercase letters.
    main is the name of the method where the java program starts a class's execution.

    --- Update ---

    I'm downloading the code for testing.

    The code has too many readLine method calls for easy testing. The code needs to contain all the user responses built into it for easier testing.
    For example define the Scanner class's constructor calls to have to responses:
    .. new Scanner("THe responses here");
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Dec 2017
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java - Node Prime Solver

    Sorry. I name the file "main" because It is a habit I got into, so I know which class is executed by the 'launcher' code. I tried to start all pre-known user responses locally, but most of the data is send via sockets, so I have to store is once I receive it (dynamically). I didn't think that was how Scanners worked. Sorry, I did all of this to the best of my abilities.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,404
    Thanks
    53
    Thanked 2,399 Times in 2,352 Posts

    Default Re: Java - Node Prime Solver

    Can you change the Scanner constructors so that they provide the correct responses to save a tester from having to enter them and to make sure the correct values are entered?

    Ideally the code for testing should start and run the code for the initial testing. When the paths and protocols have been checked out, then worry about supplying user input.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Dec 2017
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java - Node Prime Solver

    I can try, but most of that information isn't automatically know, which is why I ask. The IP is the IP of a local server since I don't run a publically accessible server. The port is because sometimes the port doesn't assign itself properly, giving you a different port. The only one I could easily change is the threads because that is up to preference. It is kinda like running a bitcoin mining pool. The server software starts the pool, and the bots/clients get the input value and return the status (true=prime, false=not_prime). The server identifier isn't important at the moment, in the furture I plan on using that for verification, but for now, type in whatever you want.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,404
    Thanks
    53
    Thanked 2,399 Times in 2,352 Posts

    Default Re: Java - Node Prime Solver

    type in whatever you want.
    I tried that, but the code does not work without the correct input.


    the server is using a port not specified by the code.
    Where is that shown in the debug output? Post the debug output and add some comments where that is shown.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 3
    Last Post: January 16th, 2014, 05:00 PM
  2. Java XML: IndexOutOfBoundsException When appending a node
    By priere in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 4th, 2013, 09:36 PM
  3. Wireless sensor node in java
    By jeniferrubys in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 28th, 2013, 02:28 AM
  4. Prime number solver.
    By Danny123 in forum What's Wrong With My Code?
    Replies: 17
    Last Post: June 4th, 2012, 05:30 AM
  5. Java Newbie: How to Code Node and its Neighbors?
    By ke3pup in forum Java Theory & Questions
    Replies: 0
    Last Post: April 20th, 2010, 01:00 AM