hate these ads?, log in or register to hide them
Page 1 of 8 1234 ... LastLast
Results 1 to 20 of 152

Thread: Dumb Programming Questions - Pro Programming Answers Megathread!

  1. #1
    Mrenda's Avatar
    Join Date
    April 9, 2011
    Posts
    1,978

    Dumb Programming Questions - Pro Programming Answers Megathread!

    I figured with a few people talking about learning programming, one of these might come in handy.

    My problem is with Java. I know there's a better way of doing things, this is purely for an assignment I have to do about packages, and abstract classes, etc. so I don't care about that. I just need some code to fill in for the class itself, so I'm using getters and setters.

    These are the two classes I have: "Fruit" an abstract superclass in a "Food" package, and an "Apple" subclass that extends the abstract "Fruit" superclass, although the "Apple" subclass is in the default package.

    Code:
     
        package food;
        public abstract class Fruit {
                public boolean poisonous;
                public String fruitName;
                public abstract void setFruitName();
                public abstract void setPoisonous();
                public abstract String getFruitName();
                public abstract Boolean isPoisonous();
        }
    Code:
     import food.Fruit;
        class Apple extends Fruit {
                public void setFruitName(String currentName){
                        fruitName = currentName;
                }
                public String getFruitName(){
                        return fruitName;
                }
                public void setPoisonous(boolean currentPoisonous){
                        poisonous = currentPoisonous;          
                }
                public Boolean isPoisonous(){
                        return poisonous;
                }
        }
    This is the problem that's showing up for Ecplise;
    Code:
    Multiple markers at this line
    	- The type Apple must implement the inherited abstract method 
    	 Fruit.setFruitName()
    	- The type Apple must implement the inherited abstract method 
    	 Fruit.setPoisonous()
    	- Breakpoint:Apple
    I would run it through the compiler for the errors, but I figure I need a main method, and I'm not too sure how I go about implementing that (I'm on the first chapter of Oracle's recommended Java book, and they don't require the main method.)

    Is Eclipse just being a bitch (I hope so.) I think this is correct, but I don't want to submit it before I know it's correct.

  2. #2
    Donor Aea's Avatar
    Join Date
    April 13, 2011
    Location
    Austin
    Posts
    1,918
    Your signatures don't match, should be.

    public abstract void setFruitName(String currentName)
    public abstract void setPoisonous(boolean currentPoisonous)

  3. #3
    Mrenda's Avatar
    Join Date
    April 9, 2011
    Posts
    1,978
    Cheers Aea. The book says that you don't have to do stuff, for the methods in the abstract class, I thought that meant declaring parameters types(?) as well as between the curly brackets.

    "Dumb Programming Questions - Pro Programming Answers" FIRST GREAT SUCCESS

  4. #4
    kzig's Avatar
    Join Date
    April 9, 2011
    Location
    Making golden statues and raising your insurance premiums
    Posts
    801
    On the subject of good answers, let me be the first in this thread to recommend www.stackoverflow.com for this sort of thing.

  5. #5

    Join Date
    April 10, 2011
    Posts
    7,006
    But we're reimplementing it, poorly...

    Also, I think Aea's slightly wrong, you're trying to return values from methods who have return type of void in the abstract superclass definition. So you want to change that or your methods furthur, as well as the parameters part.

  6. #6
    Donor Aea's Avatar
    Join Date
    April 13, 2011
    Location
    Austin
    Posts
    1,918
    Quote Originally Posted by Daneel Trevize View Post
    But we're reimplementing it, poorly...

    Also, I think Aea's slightly wrong, you're trying to return values from methods who have return type of void in the abstract superclass definition. So you want to change that or your methods furthur, as well as the parameters part.
    I'm not going to bother compiling that code, but I am pretty certain I am not wrong.

  7. #7
    Donor Sponk's Avatar
    Join Date
    April 10, 2011
    Location
    AU TZ
    Posts
    7,783
    Quote Originally Posted by Buceph View Post
    These are the two classes I have: "Fruit" an abstract superclass in a "Food" package, and an "Apple" subclass that extends the abstract "Fruit" superclass, although the "Apple" subclass is in the default package.

    [snip]
    try something like this.

    Code:
        package food;
        /** Non-retarded way to define a Fruit. */
        public interface Fruit {
                boolean isPoisonous();
                String getName();
        }
    Code:
    import food.Fruit;
    /** Note never make an abstract method you don't want every. single. subclass to implement. 
    Thus, an abstract fruit that allows a setPoisonous() method is quite retarded, 
    unless you are a witch trying to kill Snow White.
    
    This is why everyone favours composition over inheritance.
    */
        public abstract class AbstractFruit implements Fruit {
                // Never fucking set fields public. Only set protected if you really need access via subclass.
                // at all other times, they can use the accessor/mutator methods instead of messing with the internals of a class.
                private boolean poisonous;
                private String fruitName;
    
                public void setFruitName(String name) { fruitName = name;}
                public void setPoisonous(boolean poisonous)  {this.poisonous = poisonous;}
                @Override
                public String getFruitName() {return fruitName;}
                @Override
                public Boolean isPoisonous() {return poisonous;}
        }
    Code:
     
        import food.Fruit;
    
        class Apple extends AbstractFruit {
                public Apple() {
                       setFruitName("Granny Smith");
                       setPoisonous(false);
                }
        }

    Then you can run
    Code:
       Apple apple = new Apple();
       apple.setPoisonous(true);
       Logger.getLogger(getClass()).debug("cackle cackle cackle");
    but you will also find

    Code:
       Fruit apple = new Apple();
       apple.setPoisonous(true); // this will cause a compile error because the interface Fruit only has getters.
    Last edited by Sponk; February 16 2012 at 05:44:52 AM.
    Contract stuff to Seraphina Amaranth.

    "You give me the awful impression - I hate to have to say - of someone who hasn't read any of the arguments against your position. Ever."

  8. #8
    Lana Torrin's Avatar
    Join Date
    April 13, 2011
    Location
    Bonding around
    Posts
    9,071
    Are we just doing java in here??

    In powershell why the fuck cant I compare a string against a constant..

    Code:
    if($snapname -eq "_VCB-BACKUP_") {
    with NEVER enter the code block no matter what.. If I get it to print both to the screen its identical..


    Its pissing me off because its not rocket science, its just a fucking compare of 2 strings.. I HATE YOU SO MUCH POWERSHELL!!!
    Quote Originally Posted by lubica
    And her name was Limul Azgoden, a lowly peasant girl.
    < Jolin> you're prety too LanaTorrin
    Clearly mafia.

  9. #9

    Join Date
    April 10, 2011
    Posts
    7,006
    A quick google about didn't seem to suggest a common problem.
    Have you tried $snapname.CompareTo("_VCB-BACKUP_")? It will make it case sensititive in that form but there are options.
    Failing that
    PowerShell employs both single and double quotes, however they have different purposes. Double quotes expand the enclosed string, whereas single quotes treat the string as a literal. What ever you do, avoid the trap of two single quotes (ASCII decimal 039) when you need a double quote (ASCII decimal 034).
    Either a typo or a Type problem.

  10. #10
    Redclaws's Avatar
    Join Date
    April 9, 2011
    Posts
    832
    I'm guessing not many people here work with Microsoft Dynamics NAV... If you have a choice, simply don't.

  11. #11

    Join Date
    September 13, 2011
    Location
    Norway
    Posts
    573
    Could somebody explain to me what happens in the background during this kind of processing (look at the psuedo-code below, there is no multi-threading involved)? In my mind, this code does not scale well, but I'm sure that I underestimate computer capabilities because the code below should be able to loop at least 1,000 every second?

    Code:
    ** LOTS OF CODE FUNCTIONS AND CLASSES
    
    while running eq true
      check socket for new connection //what happens if a connection attempt is made after this line is run? is there a buffer somewhere in the network driver perhaps or what?
        process new connection //we process the connection and put it in a list with all associated data
          if process slow //we dont want to wait if there is latency, we dont want to introduce lag?
            what do we do here? 
      
      foreach connected client
        foreach new command //how would one check for commands from the client if the commands are not sent when this line runs?
          process commands
          if command eq send message to all clients //we send message to all clients
            foreach connected client //loop through the client list
              send message //execute send
    
      DO SOME OTHER SENSIBLE SHIT
    end while

  12. #12
    balistic void's Avatar
    Join Date
    May 5, 2011
    Location
    Dublin/London
    Posts
    1,825
    Depends on the underlying socket architecture.

    This IS likely to be multithreaded, just hidden from you. Depends on the multiplexing method used underneath, POSIX vs windoze model. If you wrote raw socket code you would see what is actually happening. Posix multiplexer method: http://linux.die.net/man/2/select -> that's the old school one I think (remember in unix a socket is same as a file). State of the art has moved on a bit I think.

    Remember TCP sockets need two way communication, so can be slow while waiting for confirmation. For really fast asynchronous stuff you want to use UDP, then your loop will machine-gun out packets as fast as possible.

    Note then, at an even lower level, the network card has a transmit and receive buffer. You can easily overfill these with crazy spinning loops and god knows what happens then

    The magic words you probably need to type into google are something like "asyncronous network programming". I did raw sockets in the 90s, but been using framework called ACE since then for this shizzle (writing mmo servers for lulz). http://www.cs.wustl.edu/~schmidt/ACE.html Turns out writing low latency trading systems for banks is pretty much the same as an mmo
    Last edited by balistic void; February 16 2012 at 01:42:57 PM.

  13. #13

    Join Date
    September 13, 2011
    Location
    Norway
    Posts
    573
    The reason I ask is that I can't imagine how this would've been done in the past with single core processing unless lag was norm(?), considering that the computer is sequential. I guess threading kind of goes around that, but in the end it is just sequential processing as threading does not equal multi-core? So on a basic level and dummified, CPU just switches between threads and gives them 0,1ms processing time each? So on a kernel level you'd see:

    Code:
    main kernel
      while comp eq on
        thread = 3
        KERNEL PROCESSING
    
        foreach system component
          read it cache in memory for 0,1ms
        next
        
        foreach thread
          process shits for 0,1 ms
          store in memory
        next
    loop

  14. #14
    balistic void's Avatar
    Join Date
    May 5, 2011
    Location
    Dublin/London
    Posts
    1,825
    Time-slicing yes. For io the old kernels just basically polled. That's what the select() call does, allows you to see which files (sockets) have activity and which ones don't. Don't know how modern kernels have improved on this.

  15. #15

  16. #16
    Donor
    Join Date
    April 9, 2011
    Posts
    1,090
    Quote Originally Posted by balistic void View Post
    Time-slicing yes. For io the old kernels just basically polled. That's what the select() call does, allows you to see which files (sockets) have activity and which ones don't. Don't know how modern kernels have improved on this.
    We're using this: http://libevent.org/ It's good. We're using epoll underneath as the replacement for select().
    meh

  17. #17
    halka's Avatar
    Join Date
    April 19, 2011
    Location
    Tarnished Coast
    Posts
    919
    Crossposting from my ill-conceived thread (sorz for making a mess):
    Quote Originally Posted by halka View Post
    Any PERL users here?

    TL;DR: plz skim over http://pastie.org/3683053 and tell me what I'm doing wrong.

    Long version:
    I've been trying to 'get into' PERL for several reasons, mainly because it's still considered as relatively fast for an interpreted language and because I am a fan of self-inflicted suffering. The first example is a script that looks into several mailboxes using POP3, iterates over messages stored there and if it finds one that hasn't been processed previously, generates a new e-mail notification and sends it to an operator.

    Now, I'm not saying that my first try doesn't work, but at several points I had a feeling that I'm kludging it and would like to get an outside opinion. The overall structure could definitely use a bit of refactoring; but I'm mainly interested in hearing your opinion of the language constructs used and if there are more 'elegant'.

    Line noise here: http://pastie.org/3683053
    All expressed opinions match those of my employers, hail satan

  18. #18
    smagd's Avatar
    Join Date
    April 12, 2011
    Location
    https://duckduckgo.com
    Posts
    854
    But, perl is meant for kludges. "ugly as fuck, but seems to work" is a perl design philosophy.

    That said, are you sure you don't want to do something like

    Code:
       if ($line =~ m/^From: ?"(.*)"/) {
          $from = $1;
       }
    or

    Code:
    $from = $1 if ($line =~ m/^From: ?"(.*)"/);
    or

    Code:
    $line =~ m/^From: ?"(.*)"/ && $from = $1;
    so you don't clobber $from in later lines that don't have a match? (same for $messageID)
    Quote Originally Posted by dstopia
    WHERE IS CCP AND WHAT HAVE YOU DONE WITH THEM?????

  19. #19
    Donor
    Join Date
    April 9, 2011
    Posts
    1,219
    Got a problem I really can't figure out with my Java assignment. It's a client-server setup that's supposed to implement a protocol we've designed. The code is based on some that was provided for one of the seminars we did a few weeks ago that our group has modified to allow the client to send more than one message and to accept various responses from the server, the server will eventually do all the validation on the input (almost certainly the worst way to do it but I don't trust the coding skills of the person who was working on the client to do it properly).

    The original code allowed the server to receive messages and return a basic response and the client would end as soon as it received the response from the server, unfortunately it doesn't seem to be working properly now as it does the first message-response fine but then any future messages don't seem to get to the server. I've run a packet tracer on it and it seems like the client is sending the data to the right port and it's being received but the server isn't detecting it.

    The server code is:

    Code:
    
    import java.net.*;
    import java.io.*;
    
    
    
    
    public class Server {
    
        private static String message =
    	"Welcome to CE-T ";
        private static String incoming = null;
        private static InputStream sin;
        private static OutputStream sout;
    
        private static class ServeClient extends Thread {
            private Socket sock;
    	int len = 0;
    	byte [] messBuffer = new byte [100];
            public ServeClient (Socket s) {
                sock = s;
            }
            public void run () {
                System.out.println ("** Server thread started");
                String outbuff = new String (message + "\r\f");
                try {
    		sin = sock.getInputStream ();
    		len = sin.read (messBuffer);
    		incoming = new String (messBuffer, 0, len);
                    if(validateInput(incoming, "success")) {
                        message = "message accepted at server";//outputMessage(incoming);
                        sout = sock.getOutputStream ();
                        sout.write (message.getBytes ());
                        System.out.println ("** Message sent");
                    }
    		else {
                        message = "5003";
                        sout = sock.getOutputStream ();
                        sout.write (message.getBytes ());
                        System.out.println ("** Message sent");
                    }
                }
                catch (IOException x ) {
                    System.out.println ("** Problem serving client" + x );
                }
                System.out.println ("** Server thread finished");
            }
    
            private String outputMessage(String inputMess) {
    			
    			
                return inputMess;
            }
    
            private boolean validateInput(String inputMess, String type) {
    			
                String inputMessage;
                if (inputMess.length() == 1) {
                    inputMessage = inputMess;
                }
                else {
                    inputMessage = inputMess.substring(0,2);
                }
                
                            
                inputMessage = inputMessage.trim();
                System.out.println(inputMessage);
                if ((inputMessage.equals("q"))||(inputMessage.equals("Q"))) {
                    System.out.println("output accepted");
                    if (type == "success") {
                        return true;
                    }
                    
                }
                else if ((inputMessage.equals("nu")) || (inputMessage.equals("NU"))) {
                    if (type == "success") {
                        return true;
                    }
                    else {
    					
    
                    }
                }
                else if ((inputMessage.equals("ln")) || (inputMessage.equals("LN"))) {
                    if (type == "success") {
                        return true;
                    }
                    else {
    
                    }
                }
                else if ((inputMessage.equals("tr")) || (inputMessage.equals("TR"))) {
                    if (type == "success") {
                        return true;
                    }
                    else {
    
                    }
                }
                else if (inputMessage.equals("?")) {
                    if (type == "success") {
                        return true;
                    }
                    else {
                        
                    }
                }
                return false;
            }
        }
    
        private static int getPort ()
        {
            BufferedReader in = new BufferedReader
    	    (new InputStreamReader (System.in));
            try {
                int p = 0;
                boolean incorrect;
                do {
                    System.out.print ("Enter port number: ");
                    try {
                        p = Integer.parseInt (in.readLine ());
                        try {
                            new InetSocketAddress ("0.0.0.0", p);
                            incorrect = false;
                        }
                        catch (IllegalArgumentException x) {
                            System.out.println ("Port number unreachable");
                            incorrect = true;
                        }
                    }
                    catch (NumberFormatException x) {
                        System.out.println ("I said, NUMBER!");
                        incorrect = true;
                    }
                } while (incorrect);
                return p;
            }
            catch (IOException x) {
                throw new Error ("Unexpected error -> " + x);
            }
        }
    
        public static void main (String [] para) {
            int port = getPort ();
            try {
                ServerSocket server = new ServerSocket (port, 5);
                System.out.println ("ServerSocket created");
                while (true) {
                    System.out.println ("Ready to receive");
                    Socket socket = server.accept ();
                    System.out.println
    		    ("Connection received and " +
    		     "server thread started");
                    Thread t = new ServeClient (socket);
                    t.start ();
                }
             }
             catch (IOException x) {
                System.out.println ("Socket problem: " + x );
             }
        }
    }
    the client code is

    Code:
    
    import java.net.*;
    import java.io.*;
    import java.util.*;
    
    
    public class Main {
    
        private static BufferedReader in;
        private static Socket socket;
        private static String message;
        private static OutputStream sout;
        private static boolean checker;
        private static InetSocketAddress addr;
    
        private static InetSocketAddress readHostAndPort () {
            in = new BufferedReader
            (new InputStreamReader (System.in));
            try {
                System.out.print ("Please enter the IP Address: ");
                String h = in.readLine ();
                int p = 30;
                boolean incorrect;
                InetSocketAddress addr = null;
                do {
                    try {
                        try {
                            addr = new InetSocketAddress (h, p);
                            incorrect = false;
                        }
                        catch (IllegalArgumentException x) {
                            System.out.println ("Port Number 30 is unreachable. Closing down.");
                            incorrect = true;
                        }
                    }
                    catch (NumberFormatException x) {
                        System.out.println ("The port should be a number. Error.");
                        incorrect = true;
                    }
                } while (incorrect);
                return addr;
            }
            catch (IOException x) {
                throw new Error("Unexpected exception occurred: " + x + ". Closing down.");
            }
        }
    
        private static void receiveMessages(String id){
            int test = Integer.parseInt(id);
            
           switch(test){
            case 5001: System.out.println("Error: Incorrect number of paramaters");break;
            case 5002: System.out.println("Error: User already exists");break;
            case 5003: System.out.println("Error: Invalid Command");break;
            case 5004: System.out.println("Error: Invalid details entered");break;
            case 5005: System.out.println("Error: Session timed out");break;
            case 5006: System.out.println("Error: Server connection failure");break;
            case 9999: System.out.println("Error: Unknown error");break;
            case 0001: System.out.println("Success: Data returned");break;
            case 0002: System.out.println("Success: User Created");break;
            case 0003: System.out.println("Success: Session ID created");break;
            case 0004: System.out.println("Success: Translation request created and quotation returned");break;
            case 0005: System.out.println("Success: All usable commands returned");break;
           }
    
        }
    
        public static void main (String [] args) {
            byte [] buff = new byte [100];
            int len = 0;
            socket = new Socket ();
            checker = true;
            in = new BufferedReader
            (new InputStreamReader (System.in));
        message = "";
        addr = readHostAndPort ();
            if (addr.isUnresolved () ) {
                System.out.print ("Couldn't resolve socket address - ");
                System.out.println ("bad host = " + addr.getHostName ());
            } else {
                System.out.print ("Socket address resolved as ");
                System.out.println (addr.getHostName () +
                                   "/" + addr.getPort ());
                try {
                    System.out.println ("Trying to connect to server...");
                    socket.connect (addr);
                    System.out.println ("Connected to " +
                                       socket.getInetAddress ().getHostName ());
                    while (checker) {
                    sendMessage();
                    }
    /**        sout = socket.getOutputStream ();
            sout.write (message.getBytes ());
            System.out.println ("I've sent a message");
                    InputStream sin = socket.getInputStream ();
                    len = sin.read (buff);
                    // extract message NOT assuming last 2 bytes are "\r\f"
                    message = new String (buff,0, len);
                */}
                catch (IOException x) {
                    System.out.println ("Error occured with the connection: " + x );
                }
    
    
            }/**
            System.out.println ("Socket client finished");
            sendMessage();*/
        }
    
    
    public static void sendMessage(){
        in = new BufferedReader
        (new InputStreamReader (System.in));
        int len = 0;
        byte [] buff = new byte [100];
        System.out.println("Input a command to start: ");
        String message;
        try {
            message = in.readLine ();
            if ((message.equals("exit"))||(message.equals("EXIT"))) {
                checker = false;
            }
            } catch (IOException aardvark) {
            throw new Error ("Error in processing command");
        }
    
    
       try {
    
            sout = socket.getOutputStream ();
            sout.write (message.getBytes ());
                    InputStream sin = socket.getInputStream ();
                    len = sin.read (buff);
                    // extract message NOT assuming last 2 bytes are "\r\f"
                    message = new String (buff,0, len);
                }
                catch (IOException x) {
                    System.out.println ("Error in communicating with server: " + x );
                }
    
                if (message.length() == 4) {
                    receiveMessages(message);
                }
                else {
                    System.out.println ("Message recevied from server: " +
                                   message);
                }
            }
     }
    I can post the output from wireshark if needed. I don't see anything obviously wrong with the code as it works fine if you close the client and reopen it and send another message, it just doesn't seem to like sending and receiving more than one.

    If anyone can possibly point out either where I've gone wrong or what I need to look into then I'd be very greatful, even hints as to what I should be looking at would be a good start.

    Edit: I'm aware the code isn't commented, that will be done as soon as I figure out what is causing the problem. I'd rather have working code than well commented not-working code.
    Last edited by halbarad; April 19 2012 at 09:54:13 AM.

  20. #20
    Donor
    Join Date
    April 11, 2011
    Location
    The Netherlands
    Posts
    680
    Quote Originally Posted by halbarad View Post
    Got a problem I really can't figure out with my Java assignment. It's a client-server setup that's supposed to implement a protocol we've designed. The code is based on some that was provided for one of the seminars we did a few weeks ago that our group has modified to allow the client to send more than one message and to accept various responses from the server, the server will eventually do all the validation on the input (almost certainly the worst way to do it but I don't trust the coding skills of the person who was working on the client to do it properly).

    The original code allowed the server to receive messages and return a basic response and the client would end as soon as it received the response from the server, unfortunately it doesn't seem to be working properly now as it does the first message-response fine but then any future messages don't seem to get to the server. I've run a packet tracer on it and it seems like the client is sending the data to the right port and it's being received but the server isn't detecting it.

    The server code is:

    Code:
    
    import java.net.*;
    import java.io.*;
    
    
    
    
    public class Server {
    
        private static String message =
    	"Welcome to CE-T ";
        private static String incoming = null;
        private static InputStream sin;
        private static OutputStream sout;
    
        private static class ServeClient extends Thread {
            private Socket sock;
    	int len = 0;
    	byte [] messBuffer = new byte [100];
            public ServeClient (Socket s) {
                sock = s;
            }
            public void run () {
                System.out.println ("** Server thread started");
                String outbuff = new String (message + "\r\f");
                try {
    		sin = sock.getInputStream ();
    		len = sin.read (messBuffer);
    		incoming = new String (messBuffer, 0, len);
                    if(validateInput(incoming, "success")) {
                        message = "message accepted at server";//outputMessage(incoming);
                        sout = sock.getOutputStream ();
                        sout.write (message.getBytes ());
                        System.out.println ("** Message sent");
                    }
    		else {
                        message = "5003";
                        sout = sock.getOutputStream ();
                        sout.write (message.getBytes ());
                        System.out.println ("** Message sent");
                    }
                }
                catch (IOException x ) {
                    System.out.println ("** Problem serving client" + x );
                }
                System.out.println ("** Server thread finished");
            }
    
            private String outputMessage(String inputMess) {
    			
    			
                return inputMess;
            }
    
            private boolean validateInput(String inputMess, String type) {
    			
                String inputMessage;
                if (inputMess.length() == 1) {
                    inputMessage = inputMess;
                }
                else {
                    inputMessage = inputMess.substring(0,2);
                }
                
                            
                inputMessage = inputMessage.trim();
                System.out.println(inputMessage);
                if ((inputMessage.equals("q"))||(inputMessage.equals("Q"))) {
                    System.out.println("output accepted");
                    if (type == "success") {
                        return true;
                    }
                    
                }
                else if ((inputMessage.equals("nu")) || (inputMessage.equals("NU"))) {
                    if (type == "success") {
                        return true;
                    }
                    else {
    					
    
                    }
                }
                else if ((inputMessage.equals("ln")) || (inputMessage.equals("LN"))) {
                    if (type == "success") {
                        return true;
                    }
                    else {
    
                    }
                }
                else if ((inputMessage.equals("tr")) || (inputMessage.equals("TR"))) {
                    if (type == "success") {
                        return true;
                    }
                    else {
    
                    }
                }
                else if (inputMessage.equals("?")) {
                    if (type == "success") {
                        return true;
                    }
                    else {
                        
                    }
                }
                return false;
            }
        }
    
        private static int getPort ()
        {
            BufferedReader in = new BufferedReader
    	    (new InputStreamReader (System.in));
            try {
                int p = 0;
                boolean incorrect;
                do {
                    System.out.print ("Enter port number: ");
                    try {
                        p = Integer.parseInt (in.readLine ());
                        try {
                            new InetSocketAddress ("0.0.0.0", p);
                            incorrect = false;
                        }
                        catch (IllegalArgumentException x) {
                            System.out.println ("Port number unreachable");
                            incorrect = true;
                        }
                    }
                    catch (NumberFormatException x) {
                        System.out.println ("I said, NUMBER!");
                        incorrect = true;
                    }
                } while (incorrect);
                return p;
            }
            catch (IOException x) {
                throw new Error ("Unexpected error -> " + x);
            }
        }
    
        public static void main (String [] para) {
            int port = getPort ();
            try {
                ServerSocket server = new ServerSocket (port, 5);
                System.out.println ("ServerSocket created");
                while (true) {
                    System.out.println ("Ready to receive");
                    Socket socket = server.accept ();
                    System.out.println
    		    ("Connection received and " +
    		     "server thread started");
                    Thread t = new ServeClient (socket);
                    t.start ();
                }
             }
             catch (IOException x) {
                System.out.println ("Socket problem: " + x );
             }
        }
    }
    the client code is

    Code:
    
    import java.net.*;
    import java.io.*;
    import java.util.*;
    
    
    public class Main {
    
        private static BufferedReader in;
        private static Socket socket;
        private static String message;
        private static OutputStream sout;
        private static boolean checker;
        private static InetSocketAddress addr;
    
        private static InetSocketAddress readHostAndPort () {
            in = new BufferedReader
            (new InputStreamReader (System.in));
            try {
                System.out.print ("Please enter the IP Address: ");
                String h = in.readLine ();
                int p = 30;
                boolean incorrect;
                InetSocketAddress addr = null;
                do {
                    try {
                        try {
                            addr = new InetSocketAddress (h, p);
                            incorrect = false;
                        }
                        catch (IllegalArgumentException x) {
                            System.out.println ("Port Number 30 is unreachable. Closing down.");
                            incorrect = true;
                        }
                    }
                    catch (NumberFormatException x) {
                        System.out.println ("The port should be a number. Error.");
                        incorrect = true;
                    }
                } while (incorrect);
                return addr;
            }
            catch (IOException x) {
                throw new Error("Unexpected exception occurred: " + x + ". Closing down.");
            }
        }
    
        private static void receiveMessages(String id){
            int test = Integer.parseInt(id);
            
           switch(test){
            case 5001: System.out.println("Error: Incorrect number of paramaters");break;
            case 5002: System.out.println("Error: User already exists");break;
            case 5003: System.out.println("Error: Invalid Command");break;
            case 5004: System.out.println("Error: Invalid details entered");break;
            case 5005: System.out.println("Error: Session timed out");break;
            case 5006: System.out.println("Error: Server connection failure");break;
            case 9999: System.out.println("Error: Unknown error");break;
            case 0001: System.out.println("Success: Data returned");break;
            case 0002: System.out.println("Success: User Created");break;
            case 0003: System.out.println("Success: Session ID created");break;
            case 0004: System.out.println("Success: Translation request created and quotation returned");break;
            case 0005: System.out.println("Success: All usable commands returned");break;
           }
    
        }
    
        public static void main (String [] args) {
            byte [] buff = new byte [100];
            int len = 0;
            socket = new Socket ();
            checker = true;
            in = new BufferedReader
            (new InputStreamReader (System.in));
        message = "";
        addr = readHostAndPort ();
            if (addr.isUnresolved () ) {
                System.out.print ("Couldn't resolve socket address - ");
                System.out.println ("bad host = " + addr.getHostName ());
            } else {
                System.out.print ("Socket address resolved as ");
                System.out.println (addr.getHostName () +
                                   "/" + addr.getPort ());
                try {
                    System.out.println ("Trying to connect to server...");
                    socket.connect (addr);
                    System.out.println ("Connected to " +
                                       socket.getInetAddress ().getHostName ());
                    while (checker) {
                    sendMessage();
                    }
    /**        sout = socket.getOutputStream ();
            sout.write (message.getBytes ());
            System.out.println ("I've sent a message");
                    InputStream sin = socket.getInputStream ();
                    len = sin.read (buff);
                    // extract message NOT assuming last 2 bytes are "\r\f"
                    message = new String (buff,0, len);
                */}
                catch (IOException x) {
                    System.out.println ("Error occured with the connection: " + x );
                }
    
    
            }/**
            System.out.println ("Socket client finished");
            sendMessage();*/
        }
    
    
    public static void sendMessage(){
        in = new BufferedReader
        (new InputStreamReader (System.in));
        int len = 0;
        byte [] buff = new byte [100];
        System.out.println("Input a command to start: ");
        String message;
        try {
            message = in.readLine ();
            if ((message.equals("exit"))||(message.equals("EXIT"))) {
                checker = false;
            }
            } catch (IOException aardvark) {
            throw new Error ("Error in processing command");
        }
    
    
       try {
    
            sout = socket.getOutputStream ();
            sout.write (message.getBytes ());
                    InputStream sin = socket.getInputStream ();
                    len = sin.read (buff);
                    // extract message NOT assuming last 2 bytes are "\r\f"
                    message = new String (buff,0, len);
                }
                catch (IOException x) {
                    System.out.println ("Error in communicating with server: " + x );
                }
    
                if (message.length() == 4) {
                    receiveMessages(message);
                }
                else {
                    System.out.println ("Message recevied from server: " +
                                   message);
                }
            }
     }
    I can post the output from wireshark if needed. I don't see anything obviously wrong with the code as it works fine if you close the client and reopen it and send another message, it just doesn't seem to like sending and receiving more than one.

    If anyone can possibly point out either where I've gone wrong or what I need to look into then I'd be very greatful, even hints as to what I should be looking at would be a good start.

    Edit: I'm aware the code isn't commented, that will be done as soon as I figure out what is causing the problem. I'd rather have working code than well commented not-working code.
    Your run method should have a loop somewhere, now your server only parses one message and then the thread stops. Do you see "** Server thread finished" after the first message is handled?
    Now the socket is probably kept open when you exit the run() method, which means that the next time the thread starts up it cannot connect to the socket because it's already claimed on OS level by the now dead thread.
    It's better design to have the while loop inside the run method of your Thread and just let the main method spawn the thread.
    Then in the main method make something that monitors key input and when you hit ENTER orso it tells the thread to die.
    If you need more help, let me know and I'll skeleton it up for you.

Bookmarks

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •