【问题标题】:Send a message to specific client using sockets使用套接字向特定客户端发送消息
【发布时间】:2016-04-24 04:51:52
【问题描述】:

我有 3 个客户端使用套接字通过服务器连接。任何人都可以帮助我理解如何在不将该消息发送到客户端 2 或客户端 3 的情况下专门将消息发送到客户端 1 的概念,或者如何在不将该消息发送到客户端 1 和客户端的情况下将消息发送到客户端 2 3.对不起我的英语不好。

【问题讨论】:

  • 你的代码在哪里?到目前为止你尝试了什么。
  • 我不知道该怎么做这就是为什么我寻求帮助@Priyamal
  • stackoverflow.com/questions/36801859/… 我也回答了同样的问题,答案中有解释可以参考这个:D

标签: java


【解决方案1】:

要向客户端发送消息,您需要获取套接字的输出流,以便您可以将数据写入该流,例如,您可以执行以下操作:-

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

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 2019-08-25
    • 2020-03-06
    • 2017-08-14
    相关资源
    最近更新 更多