如何向特定客户端发送消息(JAVA)

时间:2015-01-22 17:16:18

标签: java

我想向特定客户发送消息:

/w hey there.
X:(priv)Y:hey there(what X sees in the console)

这是我的代码。当我输入它像上面的例子时,在服务器上既没有在特定客户端的控制台上也没有显示。我不明白为什么,因为我还有一个在服务器中连接的用户列表类。

     import java.net.*;
     import java.io.*;

  public class ServerPeer extends Thread{
     Socket _socket;

   public ServerPeer(Socket _socket) {
    this._socket = _socket;
}
    public  void sendMessage(String _username,String _message) throws IOException {
    ObjectOutputStream _obj = new ObjectOutputStream(
            _socket.getOutputStream());
    _obj.writeObject(new Message(_username, _message));
    _obj.flush();

}

public synchronized void run()  {
try
    {   ObjectInputStream _ois = new ObjectInputStream(_socket.getInputStream());
    Message _message;
    while (_socket.isConnected()) {

               _message = (Message) _ois.readObject();
                    String divide=_message.getAll().substring(0,_message.getAll().indexOf(":"));
        for(ServerPeer sp:Server.listofpeers)
            {  
                 if(_message.getAll().startsWith("exit"))
                    {
                        _socket.close();Server.listofpeers.remove(sp);
                    }

              if(  !(_message instanceof PrivateMessage))
              {
                  sp.sendMessage(divide,_message.getAll());


                  System.out.println( _message.getAll());
              }  

              else

                   {
                       PrivateMessage privatem=(PrivateMessage)_message;
                       String receiver=privatem.getReceiver();
                       for(String s:Server.listofusers)
                       {
                           if(s.equals(receiver))
                           {
                               sp.sendMessage(divide,privatem.getAll());
                             System.out.println(privatem.getAll());
                               break;
                           }

                       }
                   }

            }    
        _ois = new ObjectInputStream(_socket.getInputStream());


        }

   }catch(IOException e){e.printStackTrace();}
    catch(ClassNotFoundException e){e.printStackTrace();}
       }
   }

0 个答案:

没有答案