Udp服务器/客户端,java GUI,多项选择题

时间:2015-03-21 15:07:59

标签: java udp protocols

Bellow您将看到我的客户端和服务器代码。

我差不多完成了它,我的问题是,当用户提交A问题的答案时,当服务器接收到它时,我无法通过问题协议(在服务器代码内部)处理它。 显示结果,即1 / 3,0 / 3等

如果你能帮我解决这个问题,因为我已经坚持了一个星期了,试图弄清楚,为什么我不能让结果部分正常工作,我想我有一些专业在我的问题协议中有缺陷,但我没有专业知识来识别它。

这是我的服务器代码:

                import java.net.*;
            import java.io.*;

            public class UdpServer extends Thread
            {
                //final static int port = 5600;

                public static void main(String[] args) 
                {
                    try 
                    {
                        new UdpServer().startServer();//creating an object of my class to start up the server.
                    } 
                    //catch any exceptions that might occure and print the stack.
                    catch (Exception e) 
                    {
                        System.out.println("failure: " + e.getMessage());
                        e.printStackTrace();
                    }
                }

                public void startServer() throws Exception 
                {
                    DatagramSocket serverSocket = null;//intiailise the socket to null.
                    boolean listening = true;//check for connections/
                    try 
                    {
                        serverSocket = new DatagramSocket(5600);//attach a port to the server socket we are sign in this case its the port we wanted at the start.
                        byte[] receiveStuff = new byte[1024];
                        byte[] sendStuff = new byte[1024];
                        while (listening)
                        {
                            DatagramPacket Packet = new DatagramPacket(receiveStuff,receiveStuff.length);
                            serverSocket.receive(Packet);
                            InetAddress IPAddress = Packet.getAddress();
                            int port = Packet.getPort();
                            String lineInput=null, lineOutput = null;
                            QuestionLogic questionLogic = new QuestionLogic();//creating a logic section where the questions protocol takes places, this case its called question logic.
                            lineOutput = questionLogic.processInput(null);//make the output coming from the logic side, i,e fetch whatever is happening within the logic.

                            lineInput = new String (receiveStuff, 0, Packet.getLength()); 
                            System.out.println("Server Received----"+lineInput);

                            /*if(lineInput.equals("hello"))
                            {
                                lineOutput = "Thank you for using this system";
                                System.out.println(lineOutput);
                            }*/
                            Packet.setLength(receiveStuff.length);

                            lineOutput = questionLogic.processInput(lineInput);
                            System.out.println("Server Sending----"+lineOutput);
                            sendStuff = lineOutput.getBytes();
                            Packet = new DatagramPacket(sendStuff, sendStuff.length, IPAddress, port);
                            //DatagramPacket sendPacket = new DatagramPacket(sendStuff,sendStuff.length, IPAddress, port);
                            serverSocket.send(Packet);
                            Packet.setLength(sendStuff.length);

                        }
                    } 
                    catch (IOException e) 
                    {
                        System.err.println("could not connect: " );
                        System.exit(-1);
                    }


                    serverSocket.close();
                }

                //this is where the question logic get carried out, in other word a questions protocol,.

                public static class QuestionLogic 
                {
                    private static final int Hello = 0;
                    private static final int Answer = 1;
                    private static final int Result = 2;
                    private static final int question2 = 3;
                    private static final int Result2 = 4;
                    private static final int question3 = 5;
                    private static final int Result3 = 6;

                    private int state = Hello;
                    private int res = 0;
                    private String CorrectAnswer =  null;
                    //according to the client request sort out what will be happening, in different states, goin through 3 questions returning a reply each time.
                    public String processInput(String clientRequest) 
                    {       
                        String reply = null;
                        try 
                        {
                            if(clientRequest != null && clientRequest.equalsIgnoreCase("C")) 
                            {
                                res++;
                                reply = "One"+res;
                            }
                            //these were originally for testing purposes using cmd, left in here in case in the future any further testing is required      
                            if(clientRequest != null && clientRequest.equalsIgnoreCase("Hello")) 
                            {
                                state = Hello;
                            }


                            if(clientRequest != null && clientRequest.equalsIgnoreCase("B")) 
                            {
                                res++;
                                reply = "two"+res;
                            }   

                            if(clientRequest != null && clientRequest.equalsIgnoreCase("A")) 
                            {
                                res++;
                                reply = "three"+res;
                            }

                            if(clientRequest != null && clientRequest.equalsIgnoreCase("question1")) 
                            {
                                state = Answer;
                            }

                            if(clientRequest != null && clientRequest.equalsIgnoreCase("question2")) 
                            {
                                state = question2;
                            }

                            if(clientRequest != null && clientRequest.equalsIgnoreCase("question3")) 
                            {
                                state = question3;
                            }
                            if(clientRequest != null && clientRequest.equalsIgnoreCase("Result")) 
                            {
                                state = Result3;
                            }
                            if(clientRequest != null && clientRequest.equalsIgnoreCase("exit")) {
                                return "exit";
                            }
                            //starting with a connection check to confirm server is connected to client.
                            if(state == Hello) 
                            {
                                reply = "Connected, Press Next To continue";
                                state = Answer;
                            } 
                            //we begin with the first question sent to the client.
                            else if(state == Answer) 
                            {
                                reply = "Q1: (A + B)*(A+B) \n\n A)A*A + B*B \n\n B)A*A +A*B + B*B \n\n C)A*A +2*A*B + B*B \n\n ";
                            } 
                            //check if the answer from the user is the correct one, and increment or do nothing to the result


                            else if(state == question2) 
                            {
                                reply = "Q2: (A + B)*(A - B) \n\n A) A*A + 2*B*B \n\n B) A*A - B*B\n\n C)A*A -2*A*B + B*B\n\n  ";

                            }

                            else if(state == question3) 
                            {
                                reply = "Q3: sin(x)*sin(x) + cos(x)*cos(x)\n\n A)1\n\n B)2\n\n C)3\n\n";
                            }
                            //finally we printout the result at the end for the client to see.
                            else if(state == Result3) 
                            {
                                if(res == 0)
                                {
                                    reply ="Sorry you failed 0/3";
                                }
                                if(res == 1)
                                {
                                    reply ="You got 1/3";
                                }
                                if(res == 2)
                                {
                                    reply ="You got 2/3";
                                }
                                if(res == 3)
                                {
                                    reply ="You got 3/3";
                                }
                            }
                        } 
                        catch(Exception e) 
                        {
                            System.out.println("input process failed: " + e.getMessage());
                            return "exit";
                        }
                        return reply;//we return the reply from this method to be used.
                    }
                }

            }

这是我的客户代码:

                import javax.swing.*;//for the main components design (JFrame etc).
            import java.awt.*; //main GUI manipulation.
            import java.net.*;//for socket and network programming such as ServerSockets etc.
            import java.io.*; //for main editing utilities (inputs/outputs).
            import java.awt.event.*; //Event manipulation

            //creating my main client class.
            class UdpClient 
            {
                //constructor
                public static void main (String[] args)
                {
                    try
                    {   //create an object of the class where i can carry out my code.      
                        UdpClient c = new UdpClient();
                    }

                    catch(Exception ex)
                    {
                        System.out.println("Major Error" + ex.getMessage());
                        ex.printStackTrace();
                    }
                }


                //all public variables i would like to access through out my code.
                JFrame build;//the main frame of the client
                JLabel ans,Label; // labels for names and instructions.
                JComboBox options,request;
                JButton b1,b2;//2 buttons for next and exit.
                JTextArea txt1,txt3;//txt area for the actual questions.
                JTextField txt2;// txtfield to take in user answer.
                DatagramSocket clientSocket;//client socket.
                DatagramPacket sendPacket, receivePacket;
                byte[] sendData;
                byte[] receiveData;
                String clientMsg = null,serverMsg,lineInput;

                InetAddress IPAddress = null;//for hostname solutions.
                //the next few lines, their names explain what they are for.




                //the object we created earlier where the code will mainly be discussed.    
                UdpClient()
                {   
                    //creating the actual gui, addinng everything into the build, naming them, and setting their positions.
                    build = new JFrame ("Client");
                    Label = new JLabel();
                    Label.setText("Client Interface");
                    Label.setForeground(Color.blue);
                    Label.setBounds(300,0,400,50);
                    build.add(Label);

                    //creatin text area for the questions and setting colours and position              
                    txt1 = new JTextArea();
                    txt1.setBackground(Color.cyan);
                    txt1.setForeground(Color.blue);
                    txt1.setEditable(false);
                    txt1.setBounds(50,50,300,500);
                    build.add(txt1);

                    //creating text field for the answer display/
                    txt2 = new JTextField();
                    txt2.setEditable(false);
                    txt2.setBounds(500,450,50,50);
                    build.add(txt2);

                    /*/text area for the instructions of how to use the programme.
                    txt3 = new JTextArea("Instructions:\n\n Press Next to Begin\n\n Question Appears\n\n Select Answer From List\n\n Press Next\n\n Wait For Confirmation\n\n Press Next\n\n If Result Appears\n\n Press Exit\n");
                    txt3.setForeground(Color.red);
                    txt3.setBackground(Color.lightGray);
                    txt3.setEditable(false);
                    txt3.setBounds(400,150,200,270);
                    build.add(txt3);*/

                    ans = new JLabel("Answer");
                    ans.setBounds(400,450,100,50);
                    build.add(ans);

                    b1 = new JButton("Next");
                    b1.setBounds(500,500,100,50);
                    build.add(b1);

                    b2= new JButton("start");
                    b2.setBounds(400,500,100,50);
                    build.add(b2);



                    //creating a combo box for the user to choose answers from.
                    options = new JComboBox();
                    options.addItem("A");
                    options.addItem("B");
                    options.addItem("C");
                    options.addActionListener(new ActionListener()//adding actions listeners to the choices to add the answer of the user into the txt field answer area.
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                            if(options.getSelectedItem().equals("A"))
                            {
                                txt2.setText("A");
                            }

                            if(options.getSelectedItem().equals("B"))
                            {
                                txt2.setText("B");
                            }

                            if(options.getSelectedItem().equals("C"))
                            {
                                txt2.setText("C");
                            }
                        }
                    });

                    b1.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent ev)
                        {
                            if(ev.getSource() == b1)
                            {
                                try
                                {
                                    clientSocket = new DatagramSocket();
                                    sendData = new byte[1024];
                                    receiveData = new byte[1024];
                                    IPAddress = InetAddress.getByName("localhost");
                                    clientMsg = txt2.getText();
                                    sendData = clientMsg.getBytes();
                                    sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5600);
                                    clientSocket.send(sendPacket);
                                    clientSocket.close();
                                }

                                catch(UnknownHostException ex1)
                                {
                                    System.err.println("no host: ");
                                    System.exit(1);
                                }

                                catch(IOException ex1)
                                {

                                    System.exit(1);
                                }   

                            }

                        }

                    });

                    request= new JComboBox();
                    request.addItem("QuestionOne");
                    request.addItem("QuestionTwo");
                    request.addItem("QuestionThree");
                    request.addItem("Result");
                    request.addActionListener(new ActionListener()//adding actions listeners to the choices to add the answer of the user into the txt field answer area.
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                            if(request.getSelectedItem().equals("QuestionOne"))
                            {
                                try
                                {
                                    clientSocket = new DatagramSocket();
                                    sendData = new byte[1024];
                                    receiveData = new byte[1024];
                                    IPAddress = InetAddress.getByName("localhost");
                                    clientMsg = "question1";
                                    sendData = clientMsg.getBytes();
                                    sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5600);
                                    clientSocket.send(sendPacket);

                                    receivePacket = new DatagramPacket(receiveData, receiveData.length);
                                    clientSocket.receive(receivePacket);

                                    serverMsg = new String (receiveData, 0, receivePacket.getLength()); 
                                    txt1.setText(serverMsg);
                                    clientSocket.close();
                                }

                                catch(UnknownHostException ex)
                                {
                                    System.err.println("no host: ");
                                    System.exit(1);
                                }

                                catch(IOException ex)
                                {

                                    System.exit(1);
                                }   
                            }   

                            if(request.getSelectedItem().equals("QuestionTwo"))
                            {
                                try
                                {
                                    clientSocket = new DatagramSocket();
                                    sendData = new byte[1024];
                                    receiveData = new byte[1024];
                                    IPAddress = InetAddress.getByName("localhost");
                                    clientMsg = "question2";
                                    sendData = clientMsg.getBytes();
                                    sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5600);
                                    clientSocket.send(sendPacket);

                                    receivePacket = new DatagramPacket(receiveData, receiveData.length);
                                    clientSocket.receive(receivePacket);

                                    serverMsg = new String (receiveData, 0, receivePacket.getLength()); 
                                    txt1.setText(serverMsg);
                                    clientSocket.close();
                                }

                                catch(UnknownHostException ex)
                                {
                                    System.err.println("no host: ");
                                    System.exit(1);
                                }

                                catch(IOException ex)
                                {

                                    System.exit(1);
                                }   
                            }   

                            if(request.getSelectedItem().equals("QuestionThree"))
                            {
                                try
                                {
                                    clientSocket = new DatagramSocket();
                                    sendData = new byte[1024];
                                    receiveData = new byte[1024];
                                    IPAddress = InetAddress.getByName("localhost");
                                    clientMsg = "question3";
                                    sendData = clientMsg.getBytes();
                                    sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5600);
                                    clientSocket.send(sendPacket);

                                    receivePacket = new DatagramPacket(receiveData, receiveData.length);
                                    clientSocket.receive(receivePacket);

                                    serverMsg = new String (receiveData, 0, receivePacket.getLength()); 
                                    txt1.setText(serverMsg);
                                    clientSocket.close();
                                }

                                catch(UnknownHostException ex)
                                {
                                    System.err.println("no host: ");
                                    System.exit(1);
                                }

                                catch(IOException ex)
                                {

                                    System.exit(1);
                                }   
                            }   
                            if(request.getSelectedItem().equals("Result"))
                            {
                                try
                                {
                                    clientSocket = new DatagramSocket();
                                    sendData = new byte[1024];
                                    receiveData = new byte[1024];
                                    IPAddress = InetAddress.getByName("localhost");
                                    clientMsg = "Result";
                                    sendData = clientMsg.getBytes();
                                    sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5600);
                                    clientSocket.send(sendPacket);

                                    receivePacket = new DatagramPacket(receiveData, receiveData.length);
                                    clientSocket.receive(receivePacket);

                                    serverMsg = new String (receiveData, 0, receivePacket.getLength()); 
                                    txt1.setText(serverMsg);
                                    clientSocket.close();
                                }

                                catch(UnknownHostException ex)
                                {
                                    System.err.println("no host: ");
                                    System.exit(1);
                                }

                                catch(IOException ex)
                                {

                                    System.exit(1);
                                }   
                            }   

                        }
                    });
                    //start button
                    b2.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent ev1)
                        {
                            if(ev1.getSource() == b2)
                            {

                                try
                                {
                                    clientSocket = new DatagramSocket();
                                    sendData = new byte[1024];
                                    receiveData = new byte[1024];
                                    IPAddress = InetAddress.getByName("localhost");
                                    clientMsg = "Hello";
                                    sendData = clientMsg.getBytes();
                                    sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5600);
                                    clientSocket.send(sendPacket);

                                    receivePacket = new DatagramPacket(receiveData, receiveData.length);
                                    clientSocket.receive(receivePacket);

                                    serverMsg = new String (receiveData, 0, receivePacket.getLength()); 
                                    txt1.setText(serverMsg);
                                    clientSocket.close();
                                }

                                catch(UnknownHostException e)
                                {
                                    System.err.println("no host: ");
                                    System.exit(1);
                                }

                                catch(IOException e)
                                {

                                    System.exit(1);
                                }   

                            }
                        }
                    });
                    options.setBounds(450,450,50,50);
                    request.setBounds(400,150,200,270);
                    build.add(options);
                    build.add(request);

                    build.setLayout(null);//setting build layout.
                    build.setSize(700,600);//the size of the main window.
                    build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//close when X is pressed.
                    build.setVisible(true);//enable it so it appears.
                    build.setResizable(false);//make it a fixed sized so user cant change it, e.g maximize it.

                    //a try catch, to do all the networking aspect of the client side inside of.    

                }
            }

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,最终使用数据库来解决问题。