简体   繁体   中英

Send a message to specific client using sockets

I have 3 clients connected through server using sockets. Can any one help me in understanding the concept of how can i send the message to client#1 specifically without sending that message to client 2 or client 3 or how can i send the message to client 2 without sending that message to client 1 and client 3.Sorry for my bad English.

To Send a message to a client you need to get the output stream of the socket so that you could write data to that stream for example you could do something like :-

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;
}

To read the message on the other end get the sockets inputStream and read data from it as follows :-

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 "";
}

the socket that you write to must be the client that you need to send the message to, moreover the client must be ready to read that message at that time, here is a basic Client server program Connect multiple clients to one server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM