简体   繁体   中英

Java Socket in.readLine NULL

It is the first time when I learn to use Socket. I got some problems that I can not understand.

I just don't know why the in.readLine() in the server class always get null and the action in the client class is never executed.

This is the Server class: (I didn't show the imports, they are right)

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?");
                }
            }
    }
}

}

this is the client class:

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

}

It returns null when the peer has closed the connection. It's the first thing you should check for, every time you call it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM