Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 除了初始确认之外,此简单服务器客户端程序不会发送/接收数据。为什么?_Java_Multithreading_Sockets_User Interface - Fatal编程技术网

Java 除了初始确认之外,此简单服务器客户端程序不会发送/接收数据。为什么?

Java 除了初始确认之外,此简单服务器客户端程序不会发送/接收数据。为什么?,java,multithreading,sockets,user-interface,Java,Multithreading,Sockets,User Interface,我正在为我的Comp Sci Java类做最后一个项目,所以我的想法是这是一个简单的服务器-客户端聊天室。当然,我的老师只对AP课程的各个方面非常精通,对制作这样一个程序所需的任何组件都知之甚少,所以我或多或少都是靠自己。我一直在使用各种StackOverflow帖子和其他套接字程序的示例来反向工程套接字,并找出如何使用它们,但显然,GUI无法使用检查接收到的消息所需的无限循环进行更新,因此我返回谷歌,以寻找更好的方法来监视消息。我想出了一个尝试使用propertyChange监听器的方法,这显

我正在为我的Comp Sci Java类做最后一个项目,所以我的想法是这是一个简单的服务器-客户端聊天室。当然,我的老师只对AP课程的各个方面非常精通,对制作这样一个程序所需的任何组件都知之甚少,所以我或多或少都是靠自己。我一直在使用各种StackOverflow帖子和其他套接字程序的示例来反向工程套接字,并找出如何使用它们,但显然,GUI无法使用检查接收到的消息所需的无限循环进行更新,因此我返回谷歌,以寻找更好的方法来监视消息。我想出了一个尝试使用propertyChange监听器的方法,这显然是多线程处理时使用的方法,这是另一个我和老师都不知道的方法。我找到了一个非常简单易懂的示例,并运行了它。不幸的是,除了最初确认服务器和客户端进行了联系之外,两个程序之间似乎没有传递任何数据。以下是客户端代码:

import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

class ClientRunnable extends newClient implements Runnable {
    public Socket sock = new Socket("127.0.0.1", 2702);
    public BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
    public String receptive = new String();
    public String sendToMessage = new String();
    public ClientRunnable() throws IOException, InterruptedException {
    }
    @SuppressWarnings("deprecation")
    protected void initUI(ClientRunnable runnable) throws IOException, InterruptedException {
        String wrongSizeMSG = "Your username is not the right size.  It must be at least 4 characters and \nno larger than 20 characters.";
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        frame.show();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel lblUsername = new JLabel("Please insert your username:");
        lblUsername.setBounds(131, 100, 172, 14);
        frame.getContentPane().add(lblUsername);
        lblUsername.show();
        UNInput = new JTextField();
        UNInput.setBounds(139, 125, 146, 20);
        frame.getContentPane().add(UNInput);
        UNInput.setColumns(10);
        UNInput.show();
        JButton btnGo = new JButton("GO!");
        btnGo.setBounds(170, 156, 89, 23);
        frame.getContentPane().add(btnGo);
        btnGo.show();

        JScrollPane scroll = new JScrollPane(msgDisplay);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
        frame.getContentPane().add(scroll);
        JLabel lblWrongSize = new JLabel(wrongSizeMSG);
        lblWrongSize.setForeground(Color.RED);
        lblWrongSize.setBounds(10, 172, 414, 50);
        lblWrongSize.hide();
        frame.getContentPane().add(lblWrongSize);
        msgDisplay = new JTextArea();
        msgDisplay.setBounds(10, 11, 414, 168);
        frame.getContentPane().add(msgDisplay);
        msgDisplay.setColumns(10);
        msgDisplay.hide();
        msgDisplay.setEditable(false);
        msgDisplay.setText("");
        JLabel lblPrompt = new JLabel("Type:");
        lblPrompt.setBounds(10, 190, 46, 14);
        frame.getContentPane().add(lblPrompt);
        lblPrompt.hide();
        txtEditor = new JTextField();
        txtEditor.setBounds(10, 215, 414, 35);
        frame.getContentPane().add(txtEditor);
        txtEditor.setColumns(10);
        txtEditor.hide();
        BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
        OutputStream ostream = sock.getOutputStream();
        PrintWriter pwrite = new PrintWriter(ostream, true);
        msgDisplay.setText("Start the chat, type and press Enter key.\n");
        pwrite.println("Success");
        btnGo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                username = UNInput.getText();
                System.out.println(username);
                UNInput.setText("");
                if(!(username.toCharArray().length < 4 || username.toCharArray().length > 20)){
                    btnGo.hide();
                    lblUsername.hide();
                    UNInput.hide();
                    lblWrongSize.hide();
                    msgDisplay.show();
                    lblPrompt.show();
                    txtEditor.show();
                } // if
                else {
                    lblWrongSize.show();    
                }
            }   
        });
        txtEditor.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                sendMessage = username + "> " + txtEditor.getText() + "\n";
                txtEditor.setText("");
                pwrite.print(sendMessage);
                msgDisplay.setText(msgDisplay.getText() + sendMessage);
                pwrite.flush();
            }
        });
    }

    private PropertyChangeSupport PCS = new PropertyChangeSupport(this);

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        PCS.addPropertyChangeListener(listener);
    }

    @Override
    public void run() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e){
            e.printStackTrace();    
        } // try-catch
        try {
            setReceiveRead();
        } catch (IOException e) {
            e.printStackTrace();
        } // try-catch
    } // run

    public void setReceiveRead() throws IOException {
        receptive = receiveRead.readLine();
        PCS.firePropertyChange("In", receptive == null, receptive != null);
    }

    public void propertyChange(PropertyChangeEvent e) {
        newClient.msgDisplay.setText(newClient.msgDisplay.getText() + receptive + "\n");
    }
} // Runnable

public class newClient{

    protected JFrame frame;
    protected JTextField UNInput;
    public static JTextArea msgDisplay;
    protected JTextField txtEditor;
    public Socket sock;
    public InputStream istream;

    public newClient() throws UnknownHostException, IOException {
        sock = new Socket("127.0.0.1", 2702);
        istream = sock.getInputStream();
    }
    public BufferedReader receiveRead = new BufferedReader(InputStreamReader(istream));
    public String receptive = new String();

    public JTextArea getMsgDisplay() {
        return msgDisplay;
    }

    public static void main(String[] args) throws IOException,     
        InterruptedException {
            final ClientRunnable runnable = new ClientRunnable();
            SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.initUI(runnable);
                    System.out.println("check there");
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        new Thread(runnable).start();
        System.out.println("Check here");
    }
    public static String username = new String();
    public static String receiveMessage, sendMessage = null;  
}
我一次只使用一个GUI,因此服务器代码更倾向于数据传输。你能看出为什么客户既不接收也不发送数据的明显原因吗?在以前版本的客户端中,存在一种中断的对话形式,出于某种原因,连接双方都必须在接收和记录任何一方之前键入内容,因此我假设问题至少主要在于客户端代码。谢谢你的帮助

更新
感谢可怕的袋熊指出了我在服务器代码中的错误。我已经更新了代码以反映这一点,并且还修改了代码以修复一个同时打开两个窗口的错误。我仍然不知道代码哪里出了问题。任何其他帮助都将不胜感激。再次感谢。

您再次阻塞等待输入

一次

两次

改为

sendMessage = "Server> "
        + "" + receiveMessage; 

当readLine返回null时,您需要退出读取循环。不要忽视例外情况。
receiveMessage = receiveRead.readLine()
sendMessage = "Server> "
        + "" + keyRead.readLine(); 
sendMessage = "Server> "
        + "" + receiveMessage;