【发布时间】:2016-05-02 17:35:23
【问题描述】:
假设我有 3 个班级。类是 Login、HandleMultipleClients 和 LiveMonitoring 类。在登录类中,我将服务器连接到多个客户端,并将套接字发送到 Handle 多个类。在此类中,我正在制作连接到服务器的客户端列表并将这些客户端放入数组中。在 HandleMultipleClients 中还有一个函数可以根据 ipaddress 将消息发送到我选择的特定客户端。现在在实时监控类中,我想向特定客户端发送消息,我将 handlemultipleclients 称为 new Handlemultipleclients() 并创建一个对象,因此这个新对象没有像上面那样的任何客户端列表。我想知道那里我不需要创建handlemultipleclients类的新对象的任何方法 我的代码是
public class Login implements Runnable {
@Override
public void run() {
try {
serverSock = new ServerSocket(2101);
while (true) {
sock = serverSock.accept();
LiveMOnitoring l=new LiveMOnitoring(sock);
System.out.println(sock);
//clients.put(soc.getPort(),soc);
}
}
}
}
public HandleMultipleClients(Socket sock) {
soc=sock;
clients.put(soc.getPort(),soc);
}
public void messagetospecificclients(String ipaddress,String choice) throws IOException, InterruptedException {
System.out.print(ipaddress+"\n"+choice);
for (Iterator<Integer> iter = clients.keySet().iterator(); iter.hasNext(); ) {
System.out.print("ok1");
int key = iter.next();
java.net.Socket client = clients.get(key);
InetAddress zee = client.getInetAddress();
String s = zee.getHostAddress();
System.out.print(s);
if (zee.getHostAddress().equals(ipaddress)) {
System.out.print("ok2");
dos =new DataOutputStream(client.getOutputStream());
dos.writeUTF(choice);
}
}
}
public class LiveMOnitoring extends javax.swing.JFrame {
static Socket csocket;
DataOutputStream dos;
Map<Integer, java.net.Socket> clients = new HashMap<Integer, java.net.Socket> ();
private void ApplicationsActionPerformed(java.awt.event.ActionEvent evt) {
h.messagetospecificclients();
}
}
【问题讨论】:
标签: java