gpt4 book ai didi

java - 在java中使用JButton向客户端发送消息

转载 作者:太空宇宙 更新时间:2023-11-04 13:56:50 25 4
gpt4 key购买 nike

我有一个 Java 程序,每当新客户端连接到我的服务器程序时,就会生成运行时 JButton。仅当单击为特定客户端分配的 JButton 时,我才需要向特定客户端发送消息。

void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton2.setText("Server Running!");
jButton2.setEnabled(false);
try {
while (true) {

socket = listener.accept();
try {

// System.out.println("Client connected from " + socket.getLocalAddress().getHostName());
clientIP= socket.getLocalAddress().getHostName();
buttons.add(new JButton(clientIP));
displayButton(buttons.get(clientNumber),clientNumber);
clientNumber++;

}
finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
catch (IOException ex) {
Logger.getLogger(Test_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}

我尝试过类似的事情。

public void actionPerformed( ActionEvent e ) throws IOException{
if ( e.getSource() == buttons.get(1) )
{
String thisIP = buttons.get(1).getText();
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);

out.println("hey");
JOptionPane.showMessageDialog(null,"gfb");
}
}

这些是全局宣布的:

String clientIP = "";
int clientNumber = 0;
ArrayList<JButton> buttons = new ArrayList<JButton>();
Socket socket;

最佳答案

这是修改为使用 TreeMap(排序的 HashMap)而不是 ArrayList 的代码,其中每个按钮都映射到套接字对象,请注意套接字不再是全局的。如果有不清楚的地方请告诉我。

  int clientNumber = 0;
TreeMap buttonsMap = new TreeMap();
buttonListener blistener = new buttonListener();
void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton2.setText("Server Running!");
jButton2.setEnabled(false);
try {
while (true) {

Socket socket = listener.accept();
try {

// System.out.println("Client connected from " + socket.getLocalAddress().getHostName());
String clientIP= socket.getLocalAddress().getHostName();
JButton button = new JButton(clientIP);
button.addActionListener(blistner);
buttonsMap.put(button, socket);
displayButton(button,clientNumber);
clientNumber++;

}
catch(Exception e)
{
}
}
}
finally {
listener.close();
}
}
catch (IOException ex) {
Logger.getLogger(Test_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}



private class buttonListener implements ActionListener
{
public void actionPerformed( ActionEvent e ) throws IOException{
if ( JButton button= e.getSource())
{
Socket socket = (Socket)buttonsMap.get(button);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);

out.println("hey");
JOptionPane.showMessageDialog(null,"gfb");
}
}
}

关于java - 在java中使用JButton向客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com