为什么我的客户端(即时消息)无法连接到我的服务器(即时消息)?

时间:2015-07-07 18:06:53

标签: java jframe client server

我正在观看这个人建立即时消息的教程,但是在某个地方我搞砸了,我无法弄清楚我做错了什么。这是我的代码......

服务器主类:

    Server GUI = new Server();
    GUI.startRunning();
   }
}

服务器类:

private JTextField userText;
private JTextArea chatWindow;
private ObjectInputStream input;
private ObjectOutputStream output;
private ServerSocket server;
private Socket connection;

// constructor
public Server() {
    super("HPIM");
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            sendMessage(event.getActionCommand());
            userText.setText("");
        }

    });
    add(userText, BorderLayout.SOUTH);
    chatWindow = new JTextArea();
    chatWindow.setEditable(false);
    add(new JScrollPane(chatWindow));
    setVisible(true);
    setSize(300, 150);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

// set up and run the server
public void startRunning() {
    try {
        server = new ServerSocket(6789, 100);
        while (true) {
            try {
                waitForConnection();
                setupStreams();
                whileChatting();
            } catch (EOFException eofException) {
                showMessage("\n Server ended the connection!");
            } finally {
                closeCrap();
            }

        }
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}

// wait for connection, then display connection information
private void waitForConnection() throws IOException {
    showMessage(" Waiting for someone to connect... \n");
    connection = server.accept();
    showMessage(" Now connected to "
            + connection.getInetAddress().getHostName());
}

// get stream to send and receive data
private void setupStreams() throws IOException {
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();

    input = new ObjectInputStream(connection.getInputStream());

    showMessage("\n The streams are now setup. \n");
}

// during the chat conversation
private void whileChatting() throws IOException {
    String message = "You are now connected!";
    sendMessage(message);
    ableToType(true);
    do {
        try {
            message = (String) input.readObject();
            showMessage("\n" + message);
        } catch (ClassNotFoundException classNotFoundException) {
            showMessage("\n Not sure what that user sent");
        }
    } while (!message.equals("CLIENT - END"));
}

// close streams and sockets after you are done chatting
private void closeCrap() {
    showMessage("\n Closing connections... \n");
    ableToType(false);
    try {
        input.close();
        output.close();
        connection.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}

// send message to client
private void sendMessage(String message) {
    try {
        output.writeObject("SERVER - " + message);
        output.flush();
        showMessage("\n SERVER - " + message);
    } catch (IOException ioException) {
        chatWindow.append("\n ERROR: CAN NOT SEND MESSAGE");
    }
}

// updates chat window
private void showMessage(final String text) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            chatWindow.append(text);
        }

    });
}

// let the user type stuff into their box
public void ableToType(final boolean TOF) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            userText.setEditable(TOF);
        }
    });
  }

}

客户主要类:

Client client;
client = new Client("127.0.0.1");
client.startRunning();
 }
}

客户类:

private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;

// constructor
public Client(String host) {
    super("HPIM Client");
    serverIP = host;
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            sendMessage(event.getActionCommand());
            userText.setText("");
        }

    });
    add(userText, BorderLayout.SOUTH);
    chatWindow = new JTextArea();
    add(new JScrollPane(chatWindow), BorderLayout.CENTER);
    setVisible(true);
    setSize(300, 150);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

// connect to server
public void startRunning() {
    try {
        connectToServer();
        whileChatting();
        setupStreams();
    } catch (EOFException eofException) {
        showMessage("\nClient terminated connection");
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        closeCrap();
    }
}

// connect to server
private void connectToServer() throws IOException {
    showMessage("Attempting connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP), 6789);
    showMessage("Connected to: " + connection.getInetAddress().getHostName());
}

// set up streams and receive messages
private void setupStreams() throws IOException {
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\nStreams are set up \n");
}

// while chatting with server
private void whileChatting() throws IOException {
    ableToType(true);
    do {
        try {
            message = (String) input.readObject();
            showMessage("\n" + message);
        } catch (ClassNotFoundException classNotFoundException) {
            showMessage("\nNot sure what you sent");
        }
    } while (!message.equals("SERVER - END"));
}

// close the streams and sockets
private void closeCrap() {
    showMessage("\nTerminating connection");
    ableToType(false);
    try {
        output.close();
        input.close();
        connection.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}

// send messages to server
private void sendMessage(String message) {
    try {
        output.writeObject("CLIENT - " + message);
        output.flush();
        showMessage("\nCLIENT - " + message);
    } catch (IOException ioException) {
        chatWindow.append("\nCouldn't send message!");
    }
}

// change/update chatWindow
private void showMessage(final String m) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            chatWindow.append(m);
        }

    });



}

// gives or takes away permission to type in userText
private void ableToType(final boolean TOF){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            userText.setEditable(TOF);
        }

    });
  }


}

1 个答案:

答案 0 :(得分:0)

我想通了,抱歉没有解释。首先是解释...它的作用是客户端即时消息连接到本地主机上的服务器即时消息,然后您可以相互通信,直到一个用户通过关闭它或发送消息来结束应用程序”。 这是答案...... 我做错了是在客户端我在启动运行方法中只有一个while循环。