Java Socket in.readLine为NULL

时间:2016-03-20 03:58:54

标签: java sockets serversocket

这是我第一次学习使用Socket。我遇到了一些我无法理解的问题。

我只是不知道为什么服务器类中的in.readLine()始终为null,并且永远不会执行客户端类中的操作。

这是Server类:(我没有显示导入,它们是对的)

public class 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;
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

当对等方关闭连接时,它返回null。这是你每次打电话时应该检查的第一件事。