我有三个独立的类,分别是login.java,LiveMonitoring.java和HandleMultipleClients.java。以下是所有相应类的代码
Login.java
try
{
serverSock = new ServerSocket(2101);
while (true)
{
sock = serverSock.accept();
HandleMultipleClients hmc=new HandleMultipleClients();
hmc.Connect(sock);
}
HandleMultipleClients.java
public class HandleMultipleClients
{
Map<Integer, java.net.Socket> clients = new HashMap<Integer, java.net.Socket> ();
Socket soc;
ServerSocket serverSock;
DataOutputStream dos;
DataInputStream dis;
public HandleMultipleClients()
{
}
public void Connect(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);
}
LiveMonitoring.java
HandleMultipleClients hmc=new HandleMultipleClients();
try
{
hmc.messagetospecificclients("192.168.1.102","apps");
}
现在的问题是我打电话给hmc.messagetospecificclients(&#34; 192.168.1.102&#34;,&#34; apps&#34;);它转到HandleMultipleClients类,只打印IP地址和应用程序,但它没有通过for循环。请告诉我我做错了什么。
答案 0 :(得分:1)
您正在创建对象的实例并添加&#34;客户端&#34;它在这里:
HandleMultipleClients hmc=new HandleMultipleClients();
hmc.Connect(sock);
但是你永远不会在那个实例上调用messagetospecificclients()
。
然后你创建另一个实例并在这里调用该方法:
HandleMultipleClients hmc=new HandleMultipleClients();
try
{
hmc.messagetospecificclients("192.168.1.102","apps");
}
但您从未在 实例上调用Connect()
来向其添加客户端。
(作为一个类比......想象一下,你有两辆完全相同的汽车。同样的品牌,同样的型号,从同一条生产线上下来。你已经在其中一辆汽车中加油。而你正在试驾另一个。但你不能,因为它里面没有气体。)
在具有已设置值的实例上调用messagetospecificclients()
:
HandleMultipleClients hmc=new HandleMultipleClients();
hmc.Connect(sock);
try
{
hmc.messagetospecificclients("192.168.1.102","apps");
}