2016-04-23 133 views
0

我有3個客戶端通過服務器使用套接字連接。任何人都可以幫助我理解如何將消息發送到客戶端#1而不將消息發送到客戶端2或客戶端3,或者如何將消息發送到客戶端2而無需將消息發送到客戶端1和客戶端3.抱歉,我的英語不好。使用套接字發送消息給特定的客戶端

+0

wheres your code?你到目前爲止嘗試過什麼。 – Priyamal

+0

即時通訊不知道如何做到這一點,這就是爲什麼我要求幫助@Priyamal –

+0

http://stackoverflow.com/questions/36801859/simple-java-chat-server-that-only-broadcasts-to-other-clients- not-sender/36802370#36802370 我也回答過同樣的問題,在答案中,你可以參考這個答案:D – Priyamal

回答

0

將消息發送到你需要得到插座的輸出流,這樣你可以寫數據到流例如,你可以這樣做一個客戶端: -

public Boolean writeMessage(String Command) 
{ 
    try 
    { 
     byte[] message = Command.getBytes(Charset.forName("UTF-8")); // convert String to bytes 
     DataOutputStream outStream = new DataOutputStream(socket.getOutputStream()); 
     outStream.writeInt(message.length); // write length of the message 
     outStream.write(message); // write the bytes 
     return true; 
    } 
    catch (IOException e) 
    { 
    } 
    return false; 
} 

要閱讀信息在另一端得到插座InputStream和讀取其數據如下: -

public String readMessage() 
{ 
    try 
    { 
     DataInputStream dIn = new DataInputStream(socket.getInputStream()); 

     int length = dIn.readInt(); // read length of incoming message 
     if (length > 0) 
     { 
      byte[] message = new byte[length]; 
      dIn.readFully(message, 0, message.length); // read the message 
      return new String(message, Charset.forName("UTF-8")); 
     } 
    } 
    catch (IOException e) 
    { 
    } 
    return ""; 
} 

,你寫必須是你需要將郵件發送到客戶端的插座,而且客戶端必須準備好那時讀那條消息,這是一個基本的客戶端服務器程序圖Connect multiple clients to one server

相關問題