我正在尝试创建一个聊天程序,其中客户端向服务器发送消息,然后服务器将该消息发送到所有连接的客户端以显示它。该程序可以工作,但是当客户端发送消息时,只有它会收到返回的消息,而其余连接的客户端则不会收到任何信息。
客户端代码:
public class Client {
protected static JTextArea textArea = new JTextArea(20, 30);
protected static String sendMSG, getMSG;
public static void main(String[] args) throws IOException {
String hostName = args[0];
String Username = args[1];
boolean sending = true;
try (
Socket socket = new Socket(hostName, 1010);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
//frame setup
JFrame frame = new JFrame("chat client");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//text area
JScrollPane scrollPane = new JScrollPane(textArea);
//text field
JTextField MSGText = new JTextField(5);
//"send" button
JButton sMSGB = new JButton("send");
sMSGB.setPreferredSize(new Dimension(60, 30));
sMSGB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendMSG = MSGText.getText();
MSGText.setText("");
out.println("<" + Username + ">: " + sendMSG);
}
});
//panel
JPanel p = new JPanel();
p.setLayout((new BoxLayout(p, BoxLayout.PAGE_AXIS)));
p.add(Box.createVerticalStrut(5));
p.add(scrollPane);
p.add(Box.createVerticalStrut(5));
p.add(MSGText);
p.add(Box.createVerticalStrut(5));
p.add(sMSGB);
p.add(Box.createVerticalStrut(5));
frame.getContentPane().add(p);
}
}
}
}
}
白猪掌柜的
相关分类