Reputation: 573
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.
Upvotes: 1
Views: 1348
Reputation:
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
Upvotes: 0