Hello guys.
I need to write a client-server app that provides a simple Lotto server and client to generate a user-defined sequence of random numbers in the range 1 - 42. The system operates as follows:

1) Client sends a string message to the server indicating the operation to be performed and the number of random numbers to generate (e.g. “GENERATE%4”).
2) Server parses the string message and generates the random numbers using the Math::random(), Math::round() and Integer::parseInt() methods.
3) Server sends a reply string (e.g. “GEN%4%21%13%30%11%6”) to the client with the numbers generated.

That's what Im basing on now:

public class LottoClient {

    ObjectInputStream Sinput;       // to read the socker
    ObjectOutputStream Soutput; // towrite on the socket
    Socket socket;

    // Constructor connection receiving a socket number
    LottoClient(int port) {
        // we use "localhost" as host name, the server is on the same machine
        // but you can put the "real" server name or IP address
        try {
            socket = new Socket("localhost", port);
        }
        catch(Exception e) {
            System.out.println("Error connectiong to server:" + e);
            return;
        }
        System.out.println("Connection accepted " +
                socket.getInetAddress() + ":" +
                socket.getPort());

        /* Creating both Data Stream */
        try
        {
            Sinput  = new ObjectInputStream(socket.getInputStream());
            Soutput = new ObjectOutputStream(socket.getOutputStream());
        }
        catch (IOException e) {
            System.out.println("Exception creating new Input/output Streams: " + e);
            return;
        }
        // now that I have my connection
        String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";
        // send the string to the server
        System.out.println("Client sending \"" + test + "\" to serveur");
        try {
            Soutput.writeObject(test);
            Soutput.flush();
        }
        catch(IOException e) {
            System.out.println("Error writting to the socket: " + e);
            return;
        }
        // read back the answer from the server
        String response;
        try {
            response = (String) Sinput.readObject();
            System.out.println("Read back from server: " + response);
        }
        catch(Exception e) {
            System.out.println("Problem reading back from server: " + e);
        }

        try{
            Sinput.close();
            Soutput.close();
        }
        catch(Exception e) {}
    }  

    public static void main(String[] arg) {
        new LottoClient(1500);
    }
}

Recommended Answers

All 4 Replies

And other class for server:

public class LottoServer {
    private ServerSocket serverSocket;
    LottoServer(int port) {
       /* create socket server and wait for connection requests */
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("Server waiting for client on port" + serverSocket.getLocalPort());

            while (true) {
                Socket socket = serverSocket.accept(); // accept connection
                System.out.println("New client asked for connetcion");
                TcpThread t = new TcpThread(socket);    // make a thread of it

                System.out.println("Starting a thread for a new client");
                t.start();
            }

        } catch (IOException ex) {
            System.out.println("Exception on new ServerSocket " + ex);
        }
}
    // you must "run" server to have the server run as a console application
    public static void main(String[] arg) {
        //start server on port 1500
        new LottoServer(1500);
    }

    class TcpThread extends Thread {
        Socket socket;
        ObjectInputStream Sinput;
        ObjectOutputStream Soutput;

        TcpThread(Socket socket) {
            this.socket = socket;
        }
        public void run() {
            //Creating both data Stream
            System.out.println("Thread trying to create object Input/Output Stream");
            try {
                Soutput = new ObjectOutputStream(socket.getOutputStream());
                Soutput.flush();

                Sinput = new ObjectInputStream(socket.getInputStream());

            } catch (IOException e) {
                System.out.println("Exception" + e);
            return;
            }
            System.out.println("Thread waiting for a String from client");

            //read a String (which is an object)
            try {
                String str = (String) Sinput.readObject();
                str = str.toUpperCase();
                Soutput.writeObject(str);
                Soutput.flush();

            } catch (IOException  e) {
                 System .out.println("Exception reading/writing  Streams: " + e);
                 return;
            }
                 //will surely not happen with a string
                 catch (ClassNotFoundException o) {                               
                        }
                        finally {
                                try {
                                        Soutput.close();
                                        Sinput.close();
                                }
                                catch (Exception e) {                                       
                                }
                        }
                }
        }
}

In your server file line 40 and 43

Soutput = new ObjectOutputStream(socket.getOutputStream());  // line 40
Sinput = new ObjectInputStream(socket.getInputStream());     // line 43

Try this instead and let me know what happens...

Soutput = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));  // line 40
Sinput = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));     // line 43

Also, add the random number generation between lines 54 & 55.

Emm, nothing has changed.
It needs to convert from String through the convertor and pass it back to the cliend.
I have no idea how to do this...

Oh you are talking about the last part I mentioned (add codes between lines 54 & 55). Well, what you need to do are...

1)Check if the incoming string from the client (line 54) starts with "GENERATE%" substring. If it is, do the generation; otherwise, the output string to the client should be a warning of invalid message format.
2)If it passes through #1, remove the "GENERATE%" from the string using String num = str.replace("GENERATE%", "");.
3)Attempt to parse the string number obtained from #2 using Integer.parseInt(num, 10);. Remember to put in a try-catch block.
4)In the try block, iterate up to the total number from #3. Each iteration, generate a random number and append to the str (the original string) with "%" in between. Then send back the result string to the client.
5)In catch block, sent back a warning message for the invalid message format for the total number of iteration.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.