⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 triviaserver2.java

📁 java2编程21天自学通中的源码
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.util.Random;
import javax.xml.parsers.*;
import org.xml.sax.*;

public class TriviaServer2 extends Thread {
    private static final int WAIT_FOR_CLIENT = 0;
    private static final int WAIT_FOR_ANSWER = 1;
    private static final int WAIT_FOR_CONFIRM = 2;
    private String[] questions;
    private String[] answers;
    private ServerSocket sock;
    private int numQuestions;
    private int num = 0;
    private int state = WAIT_FOR_CLIENT;
    private Random rand = new Random();

    public TriviaServer2() {
        super("TriviaServer");
        try {
            sock = new ServerSocket(4413);
            System.out.println("TriviaServer up and running ...");
        } catch (IOException e) {
            System.err.println("Error: couldn't create socket.");
            System.exit(1);
        }
    }

    public static void main(String[] arguments) {
        TriviaServer2 server = new TriviaServer2();
        server.start();
    }

    public void run() {
        Socket client = null;

        // Initialize the question and answer data
        if (!loadQuiz("qna.xml")) {
            System.err.println("Error: couldn't initialize Q&A data.");
            return;
        }

        // Look for clients and ask trivia questions
        while (true) {
            // Wait for a client
            if (sock == null)
                return;
            try {
                client = sock.accept();
            } catch (IOException e) {
                System.err.println("Error: couldn't connect to client.");
                System.exit(1);
            }

            // Process questions and answers
            try {
                InputStreamReader isr = new InputStreamReader(
                    client.getInputStream());
                BufferedReader is = new BufferedReader(isr);
                PrintWriter os = new PrintWriter(new
                   BufferedOutputStream(client.getOutputStream()), false);
                String outLine;

                // Output server request
                outLine = processInput(null);
                os.println(outLine);
                os.flush();

                // Process and output user input
                while (true) {
                    String inLine = is.readLine();
                    if (inLine.length() > 0)
                        outLine = processInput(inLine);
                    else
                        outLine = processInput("");
                    os.println(outLine);
                    os.flush();
                    if (outLine.equals("Bye."))
                        break;
                }

                // Clean up
                os.close();
                is.close();
                client.close();
            } catch (Exception e) {
                System.err.println("Error: " + e);
                e.printStackTrace();
            }
        }
    }

    /* This method adds XML support to the TriviaServer application. It replaces
    loadData(), which has been deleted. All the other code in this program is
    unchanged */
    private boolean loadQuiz(String quizFile) {
        File input = new File(quizFile);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(true);
        QuizHandler quiz;
        try {
            SAXParser sax = factory.newSAXParser();
            quiz = new QuizHandler();
            sax.parse(input, quiz);
            questions = quiz.getQuestions();
            answers = quiz.getAnswers();
            numQuestions = questions.length;           
        } catch (ParserConfigurationException pce) {
            System.out.println("Could not create that parser.");
            System.out.println(pce.getMessage());
            return false;
        } catch (SAXException se) {
            System.out.println("Problem with the SAX parser.");
            System.out.println(se.getMessage());
            return false;
        } catch (IOException ioe) {
            System.out.println("Error reading file.");
            System.out.println(ioe.getMessage());
            return false;
        }
        return true;
    }

    String processInput(String inStr) {
        String outStr = null;

        switch (state) {
            case WAIT_FOR_CLIENT:
                // Ask a question
                outStr = questions[num];
                state = WAIT_FOR_ANSWER;
                break;

            case WAIT_FOR_ANSWER:
                // Check the answer
                if (inStr.equalsIgnoreCase(answers[num]))
                    outStr="\015\012That's correct! Want another (y/n)?";
                else
                    outStr="\015\012Wrong, the correct answer is "
                        + answers[num] +". Want another (y/n)?";
                state = WAIT_FOR_CONFIRM;
                break;

            case WAIT_FOR_CONFIRM:
                // See if they want another question
                if (!inStr.equalsIgnoreCase("N")) {
                    num = Math.abs(rand.nextInt()) % questions.length;
                    outStr = questions[num];
                    state = WAIT_FOR_ANSWER;
                } else {
                    outStr = "Bye.";
                    state = WAIT_FOR_CLIENT;
                }
                break;
        }
        return outStr;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -