无法从套接字输入流读取

huangapple 未分类评论49阅读模式
标题翻译

Couldn't read from socket input stream

问题

我目前正在使用ServerSocketSocket和带有JFrame界面的UI来编写一个聊天系统。但我在从Socket流中读取数据方面遇到了困难。

以下是我的服务器端代码:

ServerSocket serverSocket = new ServerSocket(PORT);
Socket socket;

systemStatus.append(displayStatus("Server starts on port: ") + serverSocket.getLocalPort() + "\n");
while (true) {
    socket = serverSocket.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(socket.getOutputStream());
    while (true) {
        String line = in.readLine();
        while (line != null) {
            line = in.readLine();
            systemStatus.append(line);
        }
    }
}

以及客户端的发送按钮代码:

log_regButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        String login = log_loginField.getText().trim();
        String pw = log_pwordField.getText().trim();
        out.write(login + "\n" + pw + "\n");
        out.flush();
    }
});

其中,systemStatus是一个JTextArea。它应该显示来自客户端界面的JTextField中的文本,但实际上却没有显示出来。有人能告诉我我做错了什么吗?

英文翻译

I'm currently programming a Chat System using ServerSocket and Socket with JFrame UI. But I'm struggling with reading from Socket Stream.

Here is my Server code:

    ServerSocket serverSocket = new ServerSocket(PORT);
    Socket socket;

        systemStatus.append(displayStatus("Server starts on port: ") + serverSocket.getLocalPort() + "\n");
        while (true) {
            socket = serverSocket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            while (true) {
                String line = in.readLine();
                while (line != null) {
                    line = in.readLine();
                    systemStatus.append(line);
                }
            }

        }

and the send button code at the Client:

    log_regButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String login = log_loginField.getText().trim();
                String pw = log_pwordField.getText().trim();
                out.write(login + "\n" + pw+"\n");
                out.flush();
            }
        });

which systemStatus is a JTextArea. It's suppose to show text from JTextField at Client Frame. But it doesn't. Could anyone show me what I am doing wrong?

huangapple
  • 本文由 发表于 2020年3月17日 02:48:46
  • 转载请务必保留本文链接:https://java.coder-hub.com/60711640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定