从聊天中读取输入 window

Read input from chat window

所以我们的老师试图帮助并为我们的聊天 server/client 作业编写了 GUI,但我不知道如何从 GUI 读取输入。无论我输入什么,它都会一直放在那里,直到我输入一些东西。我无法弄清楚如何阅读它。在一天的大部分时间里,我一直停留在这部分,我正在放弃。我将 post classes,并且我不希望代码中提出问题的答案,我只需要能够读取我在文本框中键入的任何内容!我可以想出剩下的!本来以为连接部分会是最难的,没想到输入有问题:/

服务器Class

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{

private static final int PORT = 8889;
private static ServerSocket server;
public static int connections;

public static void main(String[] args) throws IOException
{
    server = new ServerSocket(PORT);

    System.out.println("Waiting for clients to connect...");

    Socket clientConnection;
    while (true)
    {
        if (connections >=5)
        {
            clientConnection = server.accept();
            System.out.println("No more connections can be made at this time.You will be disconnected.");
            server.close();
        }

        else {
        clientConnection = server.accept();
        //CommandHandler handler = new CommandHandler(clientConnection);
        System.out.println("Client connected.");
        connections += 1;
        System.out.println("There are " + connections + "user(s) at this time");
        //Thread t = new Thread(handler);
        //t.start();
        }
    }
}
}

客户Class

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient
{
public static final String HOST= "localhost";
public static final int PORT = 8889;

private ChatWindow window;
private Socket connection;


public ChatClient()
{   
    this.window = new ChatWindow(this);

    try {
        Socket serverConnection = null;
        try {
            serverConnection = new Socket(HOST, PORT);
            ObjectInputStream reader = new ObjectInputStream(
                    serverConnection.getInputStream());
            PrintWriter writer = new PrintWriter(
                    serverConnection.getOutputStream());

            } finally {
            serverConnection.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}




public void sendMessage(String message)
{   
    //TODO - USE THE OUTPUT STREAM TO WRITE THE MESSAGE TO THE SERVER
    //       THIS METHOD IS INVOKED BY THE window WHEN THE USER ENTERS
    //       TEXT TO SEND TO THE CHAT SERVER


}


private void start()
{           
    //TODO - ADD CODE THAT WILL CONTINUOUSLY READ
            //       MESSAGES FROM THE SERVER  
            //       USE THE window.printMessage() TO DISPLAY
            //       THE MESSAGE IN THE CHAT WINDOW
}   




public static void main(String[] args)
{
    ChatClient chatClient = new ChatClient();
    chatClient.start();

}

}

聊天WindowClass

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;

@SuppressWarnings("serial")
public class ChatWindow extends JFrame
{

private ChatClient client;

private JTextArea messageArea = new JTextArea(10, 32);
private JTextField inputArea = new JTextField(32);

public ChatWindow(ChatClient theClient)
{
    this.client = theClient;

    //when the user closes the window, make sure the user is logged out.
    addWindowListener(new WindowAdapter()
    {
        public void windowClosing(WindowEvent e)
        {
            try {
                client.sendMessage("LOGOUT");
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    // GUI COMPONENTS ------------------------------------------

    // MESSAGE AREA: All messages from all clients are displayed here
    messageArea.setEditable(false);
    messageArea.setBackground(Color.LIGHT_GRAY);
    messageArea.setLineWrap(true);

    // make sure the scroll bar stays are the bottom
    DefaultCaret caret = (DefaultCaret) messageArea.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

    // INPUT AREA: Input area where client enters text message
    // The message is sent when the user presses enter
    inputArea.addActionListener(new InputAreaActionListener());

    Container content = getContentPane();
    content.add(new JScrollPane(messageArea), BorderLayout.CENTER);
    content.add(inputArea, BorderLayout.SOUTH);

    setTitle("Chat Client");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    inputArea.requestFocusInWindow();
    setVisible(true);
}

/**
 * 
 * This method adds the message to the end of the message area followed by a
 * new line character.
 * 
 * @param message
 */
public void printMessage(String message)
{
    messageArea.append(String.format("%s\n", message));
    try
    {
        messageArea.setCaretPosition(messageArea.getLineStartOffset(messageArea.getLineCount() - 1));
    }
    catch (BadLocationException e)
    {
        e.printStackTrace();
    }
}


private class InputAreaActionListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        String command = e.getActionCommand();

        // ask the chat client to send the message to the server
        try {
            client.sendMessage(command);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        inputArea.setText("");
        inputArea.requestFocusInWindow();
    }
}

}

我觉得这很简单,也许我只是看得太难或太久了。乐于接受任何帮助或批评。除了聊天 Window Class :/

之外,任何 class 都可以修改

你必须实现 sendMessage 函数,就像 TODO 消息说你可以使用 class OutputStream,在这种情况下,是 PrintWriter 实例,就像这样:

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);

这样就可以实现客户端发送消息了