使用套接字发送消息给特定的客户端
问题描述:
我有3个客户端通过服务器使用套接字连接。任何人都可以帮助我理解如何将消息发送到客户端#1而不将消息发送到客户端2或客户端3,或者如何将消息发送到客户端2而无需将消息发送到客户端1和客户端3.抱歉,我的英语不好。使用套接字发送消息给特定的客户端
答
将消息发送到你需要得到插座的输出流,这样你可以写数据到流例如,你可以这样做一个客户端: -
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
wheres your code?你到目前为止尝试过什么。 – Priyamal
即时通讯不知道如何做到这一点,这就是为什么我要求帮助@Priyamal –
http://stackoverflow.com/questions/36801859/simple-java-chat-server-that-only-broadcasts-to-other-clients- not-sender/36802370#36802370 我也回答过同样的问题,在答案中,你可以参考这个答案:D – Priyamal