簡體   English   中英

Java Socket in.readLine NULL

[英]Java Socket in.readLine NULL

這是我第一次學習使用Socket。 我遇到了一些我無法理解的問題。

我只是不知道為什么服務器類中的 in.readLine() 總是為 null 並且客戶端類中的操作永遠不會執行。

這是 Server 類:(我沒有顯示導入,它們是對的)

公共類 SetServer {

public static void main(String[] args) throws IOException {
    System.out.println("The game server is running.");
    ServerSocket listener = new ServerSocket(9898);
    try{
        while(true){
            new Game(listener.accept()).start();
        }
    } finally{
        listener.close();
    }

}


private static class Game extends Thread{
    private Socket socket;

    public Game(Socket s){
        socket = s;
    }

    public void run(){
        try{
            // Decorate the streams so we can send characters
            // and not just bytes.  Ensure output is flushed
            // after every newline.
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            out.println("You have 60 seconds every turn, get as high socre as possible");//to client
            out.println("Every time, type the index of cards you choose in such way \"xx,xx,xx(xx=1~15)\"Get Ready");//to client

            out.println("Game begins!");//to client

            //initialize a game
            CardsShown oneGame = new CardsShown();
            out.println(oneGame.toString());//to client
            long startTime = System.currentTimeMillis();
            while(true){
                long currentTime = System.currentTimeMillis();
                if(currentTime - startTime > 1800000)
                    break;
                String input = in.readLine();//from client

                if(input == null)break;



                String[] words = input.split(",");
                int[] index = new int[words.length];
                for(int i = 0; i < words.length; i++)
                    index[i] = Integer.parseInt(words[i]);
                boolean tmp = oneGame.isSet(index);
                out.println(tmp);//to client, tell him if he is right or not
                if(tmp){
                    // firstly, remove the three cards
                    for(int i = 0; i < 3; i++)
                        oneGame.cards.remove(new Integer(index[i]));
                    oneGame.setState(oneGame.getState() - 3);
                    //make up with three new cards
                    try {
                        if(oneGame.getState() == 9)
                            oneGame.fixTo12Cards();
                        if(!oneGame.setExist())
                            oneGame.fixTo15Cards();
                     } catch (Exception e) {
                        e.printStackTrace();
                        }
                    out.println(oneGame.toString());//to client, only after the last chose of client is right
                    }
                }
            out.println("Time Out");//to client
            }catch(IOException e){
                System.out.println("Error handling " + e);
            }finally{
                try {
                   socket.close();
                }catch (IOException e) {
                    System.out.println("Couldn't close a socket, what's going on?");
                }
            }
    }
}

}

這是客戶端類:

公共類 SetClient {

public int score;
private BufferedReader in;
private PrintWriter out;
private static int PORT = 9898;
private Socket socket;

private JFrame frame = new JFrame("Game Client");
private JTextField dataField = new JTextField(40);
private JTextArea messageArea = new JTextArea(8, 60);
private JTextArea cardsArea = new JTextArea(8, 60);

public SetClient() throws Exception{
    score = 0;

    // Layout GUI
    messageArea.setEditable(false);
    cardsArea.setEditable(false);
    frame.getContentPane().add(dataField, "North");
    frame.getContentPane().add(new JScrollPane(messageArea), "Center");// for response from server
    frame.getContentPane().add(new JScrollPane(cardsArea), "South");// for showing the cards

    // Add Listeners
    dataField.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

                System.out.println(score);
                System.out.println(dataField.getText());
                out.println(dataField.getText());//to server
                String response;
                try {
                    response = in.readLine();
                    if (response.equals("Time Out")) {
                        System.exit(0);
                    }
                    else if(response.equals("true")){
                        score++;
                        response = response + "\n" + "You got one point!";
                        cardsArea.setText("");
                        cardsArea.append(in.readLine() + "\n");
                    }

                } catch (IOException ex) {
                    response = "Error: " + ex;
                }
                messageArea.append(response + "\n");
                dataField.selectAll();
        }
    });
}

public void play() throws IOException{
    // Get the server address from a dialog box.
    String serverAddress = JOptionPane.showInputDialog(
        frame,
        "Enter IP Address of the Server:",
        "Welcome to the Set Game!",
        JOptionPane.QUESTION_MESSAGE);

    // Make connection and initialize streams
    Socket socket = new Socket(serverAddress, PORT);
    in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);

    for(int i = 0; i < 3; i++)
        messageArea.append(in.readLine() + "\n");
    cardsArea.append(in.readLine() + "\n");
}

private boolean wantsToPlayAgain() {
    int response = JOptionPane.showConfirmDialog(frame,
        "Want to play again?",
        "Set Game",
        JOptionPane.YES_NO_OPTION);
    frame.dispose();
    return response == JOptionPane.YES_OPTION;
}

public static void main(String[] args) throws Exception {
    while(true){
        SetClient client = new SetClient();
        client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        client.frame.pack();
        client.frame.setVisible(true);
        client.play();
        if (!client.wantsToPlayAgain()) {
            break;
        }
    }
}

}

當對等方關閉連接時,它返回 null。 這是您每次調用它時應該檢查的第一件事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM