2016-01-24 67 views
0

我正在使用java中的套接字和線程構建一個多線程示例。該服務器將同時獲得多個Socket,並且當我從服務器發送消息時,我想要客戶端的套接字返回以便我給出。 到目前爲止,我的理解是創建ArrayList,但我不知道如何將其用於我的目的。 任何人都可以幫助或給我任何線索來解決這個問題?如何將數據從服務器發送到選定的客戶端?

以下是代碼:

//服務器套接字從客戶端接受之前等待。

public class ServerSocketEntry { 
    ServerSocket ssoc; 
    Socket soc; 
    ArrayList<Socket> arrSocket = new ArrayList<Socket>(); 
    private static final int port=4853; 

public ServerSocketEntry(ServerManagement sm){ 
    try { 
     ssoc = new ServerSocket(port); 
     System.out.println("Waiting"); 
     while(true){ 
      soc=ssoc.accept(); 
      arrSocket.add(soc); 
      System.out.println("Accepted: "+soc); 
      ServerSocketThread sth = new ServerSocketThread(soc,sm); 
      sth.start(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public static void main(String[] args) { 
    ServerManagement sm = new ServerManagement(); 
    new ServerSocketEntry(sm); 
} 

} 

// threadClass using readObject(),writeObject()方法。

public class ServerSocketThread extends Thread { 
Socket soc; 
ObjectOutputStream oos; 
ObjectInputStream ois; 
ServerManagement sm; 
Food food; 

public ServerSocketThread(Socket soc,ServerManagement sm) { 
    this.soc=soc; 
    this.sm=sm; 
    try { 
     ois= new ObjectInputStream(soc.getInputStream()); 
     oos= new ObjectOutputStream(soc.getOutputStream()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public void run(){ 
    Command com; 
    while(true){ 
     try { 
      com = (Command) ois.readObject(); 
      if(com.getCommand()==Command.Member_Check){ 
       Member member = (Member) com.getObj(); 
       System.out.println("thread: "+member); 
       if(sm.checkMember(member)){ 
        com.setCommand(Command.Command_OK); 
       }else{ 
        com.setCommand(Command.Command_Fail); 
       } 
      }else if(com.getCommand()==Command.LogIn_Check){ 
       Member member = (Member) com.getObj(); 
       if(sm.checkLogIn(member)){ 
        com.setCommand(Command.Command_OK); 
       }else{ 
        com.setCommand(Command.Command_Fail); 
       } 
      }else if(com.getCommand()==Command.Food_Check){ 
       ArrayList<Food> serverArrFood = com.getFoodOrder(); 
       if(sm.checkFood(serverArrFood)){ 
        com.setCommand(Command.Command_OK); 
       }else{ 
        com.setCommand(Command.Command_Fail); 
       } 
      } 
      oos.writeObject(com); 
      oos.flush(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

} 
+0

您必須使用連接到要發送到的客戶端的套接字。這只是一個數據結構問題,而且是一個微不足道的問題。 – EJP

回答

0

然後,您可以使用哈希映射來存儲連接的客戶端,並且很容易從映射中獲取特定客戶端並將消息發送到該客戶端。在新客戶端連接到服務器時,使用客戶端的暱稱作爲密鑰和套接字作爲值。將這些值放入地圖中。例如:

Map<String, Socket> clients = new HashMap(); 
clients.put(nickname, clientSocket); 

寫入時只需通過其密鑰獲取特定客戶端。

clients.get(nickname); 

並寫入其輸出流。當一個客戶端向特定的客戶端發送消息時,它應該將接收者的暱稱作爲消息的一部分發送給服務器。

+0

感謝您的建議。這是一個非常友好的答案,對我的學習項目很有幫助! – Jin25

相關問題