简体   繁体   English

Java Socket in.readLine NULL

[英]Java Socket in.readLine NULL

It is the first time when I learn to use Socket.这是我第一次学习使用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.我只是不知道为什么服务器类中的 in.readLine() 总是为 null 并且客户端类中的操作永远不会执行。

This is the Server class: (I didn't show the imports, they are right)这是 Server 类:(我没有显示导入,它们是对的)

public class SetServer {公共类 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 {公共类 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.当对等方关闭连接时,它返回 null。 It's the first thing you should check for, every time you call it.这是您每次调用它时应该检查的第一件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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