制作即时通讯程序,运行 错误?

Making Instant Messaging Program, Running Incorrectly?

我只是 运行 连接服务器以确保其正常工作。当我 运行 ServerTest.java 时,我得到 "Closing Connections in my TextArea",但是我希望在 textField 中有 "Waiting for Someone to Connect..."。谁能告诉我,我的问题是什么?

ServerTest.java

import javax.swing.JFrame;

public class ServerTest {

    public static void main(String[] args){
        Server Spirit = new Server();
        Spirit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Spirit.startRunning();
    }
}

Server.java

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Server extends JFrame {

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

//server constructor
public Server(){
    super("SiM");
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    sendMessage(event.getActionCommand());
                    userText.setText("");
                }
            }
            );
    add(userText, BorderLayout.NORTH);
    chatWindow = new JTextArea();
    add(new JScrollPane(chatWindow));
    setSize(300,150);
    setVisible(true);

}

public void startRunning(){
    try{
        server = new ServerSocket (6798, 100); // parameters port and backlog
        while(true){
            try{
                waitForConnection();//waits for a connection
                setupStreams(); //sets up connection
                whileChatting();//once connected, sends message between each other
            }catch(EOFException eofException){              
                showMessage("\n Server Ended the Connection!"); //once streams been closed by Server
            }finally{
                closeCrap();
            }
        }
    }catch(IOException ioException){
        ioException.printStackTrace();
    }


}

//connection waiting

private void waitForConnection() throws IOException{
    showMessage("Waiting for somebody to connect... \n");
    connection = server.accept(); //listens for connection made to this socket and accepts it
    showMessage("Connected to" + connection+getInetAddress().getHostName() + " \n"); //dispays ip of connected
    }

//exchange data
private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush(); //flushes the stream
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\n Streams Accepted \n");
}

//initiates chat
private void whileChatting() throws IOException {
    String message = "You are now Connected";
    sendMessage(message);
    ableToType(true); //allows the user to type
    do{
        try{
            message = (String) input.readObject();
            showMessage("\n"+ message); //sent messages
        }catch(ClassNotFoundException classNotFoundException){ //if something odd is sent i.e string not sent
            showMessage("\n Unknown Message Sent! \n"); 
        }
    }while(!message.equals("CLIENT - END"));
}

//closes program
private void closeCrap(){
    showMessage("\n Closing Connections... \n");
    ableToType(false);
    try{
        output.close(); //closes connection from client
        input.close(); //closes connection to client
        connection.close(); //closes socket
    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

//send message to client
private void sendMessage(String message){
    try{
        output.writeObject("ADMIN/Server -  " + message);
        output.flush();
        showMessage("\nADMIN/Server -  " + message);
    }catch(IOException ioException){
        chatWindow.append("\n Message not Sent \n");
    }

}

//update chatWindow
private void showMessage(final String text){
    SwingUtilities.invokeLater( //creates thread that will update the GUI
            new Runnable(){
                public void run(){
                    chatWindow.append(text); //adds to the end of chattWindow
                }
            }
            );
}

//to type
private void ableToType(final boolean tof){
    SwingUtilities.invokeLater( //creates thread that will update the GUI
            new Runnable(){
                public void run(){
                     userText.setEditable(tof); //updates GUI, to allow you to type
                }
            }
            );
}

}

我一直在关注 TheNewBoston 教程。

我的错误是我的 waitForConnection() 构造函数

private void waitForConnection() throws IOException{
    showMessage("Waiting for somebody to connect... \n");
    connection = server.accept(); //listens for connection made to this socket and accepts it
    showMessage("Connected to" + connection+getInetAddress().getHostName() + " \n"); //dispays ip of connected
    }

第 4 行应该是“.”不是“+”

+ connection.getInetAddress().getHostName() +

输入错误。

很高兴见到客户,这样我们就可以自己测试了。但是您的结构看起来非常脆弱,每当出现异常时(在聊天程序中经常发生),您都在调用 closeCrap() 方法。所以也许您可以执行以下操作:

  public void startRunning(){
try{
    server = new ServerSocket (6798, 100); // parameters port and backlog
    while(true){
        try{
            waitForConnection();//waits for a connection
            setupStreams(); //sets up connection
            String message = whileChatting();//once connected, sends message between each other
            if(message.equals("CLIENT - END")){
                  closeCrap();
            }
        }catch(EOFException eofException){              
            showMessage("\n Server Ended the Connection!"); //once streams been closed by Server
        }
    }
}catch(IOException ioException){
    ioException.printStackTrace();
}

}

我同意它不是最优雅的,但你可以随时调整它,如果它起作用的话:)

顺便说一句。我为我的第三学期期末考试制作了这个程序, 它是一个巨大的聊天程序,使用了图形、树、堆栈、观察者模式、javafx 等。但是如果你看对了地方,你将能够挖掘出一些你需要的相同逻辑。