CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   Java multi-threaded test taker (http://www.codingforums.com/showthread.php?t=222601)

mimis40 03-28-2011 06:16 PM

Java multi-threaded test taker
 
I am in the middle of making a test taking program for my programming class. I have both a server and a client side; however, for some reason the two are not sending and receiving messages to each other like they should be doing.

Here is the code or if you would like me to send you the netbeans folder tell me your email:

Answers class:

Code:

import java.io.*;
import java.util.Scanner;

public class Answers extends javax.swing.JFrame implements Runnable{
    private PrintWriter out;
    private Scanner in;
    private String message, inMessage;
    private boolean sent = false;
   
    public Answers() {
       
        initComponents();
        this.setTitle("Answers");
   
    }
 
    public void run(){
        while(true){
            //get the message from the server
            receiveMessage(inMessage);
            if(inMessage.equals("sent")){
                sent = false;
            }
            if(inMessage.equals("new") && !sent){
                Submit.setEnabled(true);
                sent = true;
            }
        }
    }
   
   
    public void setOut(PrintWriter out) {
        this.out = out;
    }
   
    public void setIn(Scanner in){
        this.in = in;

    }

    public void sendMessage(String msg){
        out.println(msg);
        //System.out.println(msg);
    }
   
    public void receiveMessage(String msg){
        try{
            msg = in.nextLine();
        }catch(Exception e){
            System.err.println(e);
        }
    }

        private void CActionPerformed(java.awt.event.ActionEvent evt) {                                 

}                               

private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {                                     

        if(A.isSelected()){
            message = "a";
            sendMessage(message);
        }
        if(B.isSelected()){           
            message = "b";
            sendMessage(message);
        }
        if(C.isSelected()){           
            message = "c";
            sendMessage(message);
        }
        if(D.isSelected()){         
            message = "d";
            sendMessage(message);
        }
        if(E.isSelected()){         
            message = "e";
            sendMessage(message);
        }
        if(F.isSelected()){
            message = "f";
            sendMessage(message);
        }
       
        Submit.setEnabled(false);     

}                                     

        public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Answers().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                   
    private javax.swing.JRadioButton A;
    private javax.swing.JRadioButton B;
    private javax.swing.JRadioButton C;
    private javax.swing.JRadioButton D;
    private javax.swing.JRadioButton E;
    private javax.swing.JRadioButton F;
    private javax.swing.JButton Submit;
    private javax.swing.ButtonGroup gbnAnswers;
    private javax.swing.JLabel jLabel1;[/ICODE]

Client class:

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
import javax.swing.JOptionPane;


public class Client extends javax.swing.JFrame {
    private Socket echoSocket = null;
    static String username = null;
    boolean connected = false;
 
    private Scanner in = null;
    private PrintWriter out = null;
   
    public Client() {
        initComponents();
    }
    private String ipAddress = "";

   
   
    //public void setOut(PrintWriter out){
    //    out = answers.setOut(out);
    //}
           
private void DoneActionPerformed(java.awt.event.ActionEvent evt) {                                   
    ipAddress = IP.getText();
    username = Name.getText();
    Answers answers = new Answers();
    if(username.isEmpty() || ipAddress.isEmpty()){
        JOptionPane.showMessageDialog(this, "Please enter the IP address and your name");
    }
    else{
        try {
            echoSocket = new Socket(ipAddress, 7);
            out = new PrintWriter(echoSocket.getOutputStream());
            in = new Scanner(echoSocket.getInputStream());
            //user is connected
            connected = true;
            //set the inputstream and outputstream in Answers
            answers.setOut(out);
            answers.setIn(in);
           
           
           
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + ipAddress + ".");
            e.printStackTrace();
            System.exit(1);
        } catch (IOException e){
            System.err.println("IO Exception Error\n");
            e.printStackTrace();
        }
        try{
            answers.sendMessage("Hello World");
        }
        catch(Exception e){
            System.out.println("Could not connect to the server");
            e.printStackTrace();
        }
        if(connected){
            answers.run();
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Dimension screenDim = toolkit.getScreenSize();
            int answersWidth = answers.getWidth(), answersHeight = answers.getHeight();

            setVisible(false);
            answers.setDefaultCloseOperation(HIDE_ON_CLOSE);
            answers.setLocation((screenDim.width - answersWidth)/2, (screenDim.height - answersHeight)/2);
            answers.setVisible(true);
        } else{
            JOptionPane.showMessageDialog(this, "Could not connect to server, try again");
        }
           
       
    }
     
   
}                                   
 
        public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Client().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton Done;
    private javax.swing.JTextField IP;
    private javax.swing.JTextField Name;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;


Client Handler class
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientHandler implements Runnable{
    private String name;
    private Socket socket;
    PrintWriter out = null;
    private String currentMessage = "";
    private Scanner in;
    ServerControl sc;

    boolean results;
   
    public void setResults(boolean results){
        this.results = results;
    }
   
    public ClientHandler(String name, Socket socket){
        this.socket = socket;
        this.name = name; 
    }
   
    public String getCurrentMessage(){
        //send the current message
        return currentMessage;
    }

    public void resetCurrentMessage(){
        //set the current message equal to nothing
        currentMessage = "";
    }
   
   
    @Override
    public void run() {
        System.out.println("Client is ready to Listen");
        try {
            out = new PrintWriter(socket.getOutputStream(), true);
            out.flush();
            in = new Scanner(new InputStreamReader(socket.getInputStream()));
        } catch (IOException ex) {
            System.out.println("Client is not Listening");
            ex.printStackTrace();
        }
            while(true){               
                try {
                    //listen for the message from the client
                    System.out.println("Listening for Message");
                    currentMessage = in.next();
                    System.out.println(currentMessage);
                } catch (Exception x) {
                    x.printStackTrace();
                }
            }
        }
       
    }


Main class:

import java.awt.*;

public class Main extends javax.swing.JFrame {

        public Main() {
        initComponents();
        this.setTitle("Test Taker");

        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenDim = toolkit.getScreenSize();
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        int mainWidth = this.getWidth(), mainHeight = this.getHeight();
        setLocation((screenDim.width - mainWidth)/2, (screenDim.height - mainHeight)/2);
       
    }

        private void ServerActionPerformed(java.awt.event.ActionEvent evt) {                                     

    ServerControl sc = new ServerControl();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenDim = toolkit.getScreenSize();
    int scWidth = sc.getWidth(), scHeight = sc.getHeight();

    setVisible(false);
    sc.setDefaultCloseOperation(HIDE_ON_CLOSE);
    sc.setLocation((screenDim.width - scWidth)/2, (screenDim.height - scHeight)/2);
    sc.show();
   
}                                     

private void ClientActionPerformed(java.awt.event.ActionEvent evt) {                                       
    Client ipg = new Client();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenDim = toolkit.getScreenSize();
    int ipgWidth = ipg.getWidth(), ipgHeight = ipg.getHeight();

    setVisible(false);
    ipg.setDefaultCloseOperation(HIDE_ON_CLOSE);
    ipg.setLocation((screenDim.width - ipgWidth)/2, (screenDim.height - ipgHeight)/2);
    ipg.show();
       
}

        public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton Client;
    private javax.swing.JButton Server;
    private javax.swing.JLabel jLabel1;
}


Results Display class:
[ICODE]import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;

public class ResultsDisplay extends JPanel {
    private int a,b,c,d,e,f;
    FileWriter fw;
    private String currentMessage = "";
    ServerSocket serverSocket = null;
    Scanner in = null;
    PrintWriter out = null;
    static final int PORT = 7;
    ArrayList <ClientHandler> arrClients = new ArrayList<ClientHandler>();
    Socket socket;
    HashMap<ClientHandler,String> list = new HashMap<ClientHandler,String>();
    boolean finished = false;
    public ResultsDisplay(){
   
    }

    public void endProgram(String name) throws IOException{
        try {
            boolean exists = (new File(name)).exists();
            //make a new file
            if(exists){
               
            }else{
                fw = new FileWriter(name);
            }
            //write the results to the file
            for(ClientHandler cl : arrClients){
                list.get(cl);
                fw.append(list.toString() + "\n");
            }
           
        } catch (IOException ex) {
        }finally{
            //close the file
            fw.close();
            //set finished to true so all other loops close
            finished = true;
            //open the file
            String[] args = {"open", name};
            Runtime.getRuntime().exec(args);
            //exit program
            System.exit(0);
        }

    }
   
    public void resetClients(){
        //iterate through clients and send message
        for(ClientHandler cl : arrClients){
            out.println("sent");
            out.println("new");
        }
    }
 
    @Override
    public void paintComponent(Graphics g){
        //draw the graw of results
        super.paintComponent(g);
        DrawResults(g);
    }
   
    public void Connect(){
        //start connection thread to listen for users
        connect.start();
        //start listener thread to listen for in and out messages
        listener.start();
    }

    Thread listener = new Thread(){
        @Override
        public void run(){
            //while program has not ended
            while(!finished){
                //add each client in hashmap add text
                for(ClientHandler c: arrClients){
                    //if the current message isnt null, add it to the list
                    if(!c.getCurrentMessage().equals("")){
                        //TODO:  you may need to parse the current message
                        SetAnswer(c.getCurrentMessage());
                        try{
                            //get the client in the hashmap
                            list.get(c);
                            //put their answer in the hashmap
                            list.put(c, currentMessage + ", ");
                        }catch(Exception e){                         
                        }
                        c.resetCurrentMessage();
                    }
                }
            }
        }
    };

    Thread connect = new Thread(){
        @Override
        public void run(){
              ClientHandler client;
            try{
                //open server socket
                serverSocket = new ServerSocket(PORT);
                while(!finished){
                    //look for users
                    socket = serverSocket.accept();
                    Scanner intest=new Scanner(socket.getInputStream());
                    //System.out.println("Message" + intest.next());
                    //instanciating clients
                    client = new ClientHandler(Client.username, socket);
                    //start client threads for messages
                    client.run();
                    //add clients to array
                    arrClients.add(client);
                    //add client to the hashmap
                    list.put(client, "");                                             
                   
                }
                //when program is finished close server socket
                serverSocket.close();
               
            }catch (IOException ex) {
                    System.out.println("Could not initiate server socket");
            }
        }
    };

    public void SetAnswer(String answer){
        if(answer.equals("a")){
            //if answer is a then add 1 to the variable a
            a += 1;
        }
        if(answer.equals("b")){
            //if answer is b then add 1 to the variable b
            b += 1;
        }
        if(answer.equals("c")){
            //if answer is c then add 1 to the variable c
            c += 1;
        }
        if(answer.equals("d")){
            //if answer is d then add 1 to the variable d
            d += 1;
        }
        if(answer.equals("e")){
            //if answer is e then add 1 to the variable e
            e += 1;
        }
        if(answer.equals("f")){
            //if answer is f then add 1 to the variable f
            f += 1;
        }
        else{
            System.out.println("could not set answer");
        }

    }

    public void ResetScores(){
        //set all scores equal to 0
        a=0;
        b=0;
        c=0;
        d=0;
        e=0;
        f=0;
    }
   
   
    public void DrawResults(Graphics g){
        //set starting y coordinate
        int y = 36;
        //set the starting number coordinate
        int numY = 665;
        String stra = "a", strb = "b", strc= "c", strd= "d", stre= "e", strf= "f";
       
        //draw the outline of the graph
        g.drawLine(24, 36, 24, 676);
        g.drawLine(24, 676, 425, 676);
        int num = 1;
        for(int i = 0; i < 40; i++){
           
            String str = String.valueOf(num);
            g.drawLine(19, y, 24, y);
            y += 16;
            if(num<=9){
                g.drawString(str, 10, numY);
            }
            else{
                g.drawString(str, 5, numY);
            }
            num += 1;
            numY -= 16;
        }
        //draw A/B/C/D/E/F
        g.drawString(stra, 47, 690);
        g.drawString(strb, 122, 690);
        g.drawString(strc, 198, 690);
        g.drawString(strd, 272, 690);
        g.drawString(stre, 347, 690);
        g.drawString(strf, 423, 690);
           
        //draw the results     
        g.setColor(Color.BLUE);
        g.fillRect(25, 676 - (a*16), 50, a*16);
        g.setColor(Color.MAGENTA);
        g.fillRect(100, 676 - (b*16), 50, b*16);
        g.setColor(Color.GREEN);
        g.fillRect(175, 676 - (c*16), 50, c*16);
        g.setColor(Color.CYAN);
        g.fillRect(250, 676 - (d*16), 50, d*16);
        g.setColor(Color.ORANGE);
        g.fillRect(325, 676 - (e*16), 50, e*16);
        g.setColor(Color.YELLOW);
        g.fillRect(400, 676 - (f*16), 50, f*16);

        //draw lines around results
        g.setColor(Color.BLACK);
        g.drawRect(25, 676 - (a*16), 50, a*16);
        g.drawRect(100, 676 - (b*16), 50, b*16);
        g.drawRect(175, 676 - (c*16), 50, c*16);
        g.drawRect(250, 676 - (d*16), 50, d*16);
        g.drawRect(325, 676 - (e*16), 50, e*16);
        g.drawRect(400, 676 - (f*16), 50, f*16);

    }
}

If you can do anything to help it would be much appreciated, i dont know where it is going wrong. because of some character limit issues i wasnt able to post every class.

mimis40 03-31-2011 04:57 PM

can anyone please help? This is my final project for school so i need to get it finished soon.

Fou-Lu 03-31-2011 05:48 PM

This is way too much code to expect us to go through (especially since you've mentioned that its not complete), and given that its homework you cannot expect a rewrite to happen.

What has stepping through a debugger revealed for this? I've never built a client/server communication with java quite the way you have here (I've never had a reason to socket with java). In java, I'd typically throw the communication against an RMI instead as its fairly simple to use (though there is nothing wrong with socketing it if you like). The only purpose I can really see with multithreading this is to allow the server to communicate with multiple clients and push the messages around if necessary (multiple clients can see each other, also something rmi can do), much like a chat program. The other threads would be simple since they would be on the clients allowing them to receive responses at the same time they send requests (optional of course, can be updated during repaints instead).

So I guess what I'm getting at here, is I'm not really sure what kind of help you are needing to do with this. I don't have the time to even look through this much code, let alone debug it. If you can get it down to more specific problems (ie: threads failing, deadlocking, etc), then we have an actual spot to look at. But without particular issues, this is an open 'not working' application, which really isn't all that helpful I'm afraid.

mimis40 04-01-2011 02:02 PM

Thank you fou-lu for taking the time to tell me that. How about just looking in the resultsDisplay class at the threads and look in the thread in the client class and seeing where there might be problems with the message sending back and forth? thank you. As for the rmi, i will look into it. In my program i am networking the whole computer lab at my school together at the same time to take the tests the teacher gives so i thought sockets were the only way to go; however, i will look into anything else anyone has to offer.


All times are GMT +1. The time now is 05:13 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.