简体   繁体   English

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

[英]Making Instant Messaging Program, Running Incorrectly?

I am just running the server to ensure it works. 我只是在运行服务器以确保其正常工作。 When i run ServerTest.java, I get "Closing Connections in my TextArea", However I am expected to have "Waiting for Someone to Connect..." within the textField. 当我运行ServerTest.java时,出现“正在关闭TextArea中的连接”的消息,但是我希望在textField中有“正在等待某人连接...”。 Could someone tell me, what my problem is? 有人可以告诉我,我的问题是什么?

ServerTest.java 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 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
                }
            }
            );
}

}

I have been following TheNewBoston Tutorials. 我一直在关注TheNewBoston教程。

My error was my waitForConnection() constructor 我的错误是我的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
    }

On line 4 it should be "." 在第4行上,它应该为“。” not "+" 不是“ +”

+ connection.getInetAddress().getHostName() +

It was a typing error. 这是一个键入错误。

Would've been nice to see the client, so we would've been able to test it ourselfes. 见到客户会很高兴,所以我们可以自己进行测试。 But your structure just seems very fragile, whenever an exception pops, which it does quite often in chat programs, you're calling your closeCrap() method. 但是您的结构看起来非常脆弱,每当弹出异常(在聊天程序中经常发生)时,您就在调用closeCrap()方法。 so maybe you could do the following: 所以也许您可以执行以下操作:

  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();
}

} }

I agree that its not the most elegant, but you can allways adjust it, if it after it works :) 我同意它不是最优雅的,但是如果它可以正常工作,您可以对其进行调整:)

btw. 顺便说一句。 i made this program for my 3rd semester final exam, its a huge chat program that uses graphs, trees, stacks, observer pattern, javafx etc. But if you look the right places you would be able to dig out some of the same logic that you need. 我为我的第三学期期末考试制作了这个程序,它是一个庞大的聊天程序,它使用图形,树,堆栈,观察者模式,javafx等。但是,如果您查找正确的位置,则可以挖掘出一些相同的逻辑,你需要。

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

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