制作即时消息程序,运行不正确?

时间:2015-04-25 12:16:50

标签: java swing serversocket event-dispatch-thread messenger

我正在运行服务器以确保其正常运行。当我运行ServerTest.java时,我得到"关闭我的TextArea"中的连接,但是我应该有"等待某人连接......"在textField中。有人能告诉我,我的问题是什么?

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 Tutorials。

2 个答案:

答案 0 :(得分:0)

我的错误是我的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() +

这是打字错误。

答案 1 :(得分:0)

看到客户会很高兴,所以我们可以自己测试它。但是你的结构看起来非常脆弱,每当一个异常弹出,它经常在聊天程序中,你就会调用你的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等。但如果你看起来正确的地方,你将能够挖掘出你需要的一些相同的逻辑。