【问题标题】:Java private messagingJava 私人消息传递
【发布时间】:2016-04-28 07:37:25
【问题描述】:

我在 java 中遇到私人消息问题。我在用户启动客户端时询问“名称”,它是 ChatClient.java 文件中的一个变量。我已将其设为“公开”,但是当我尝试在 ChatServer.java 中调用它时,它会显示“找不到符号”。有什么帮助吗?同样在这个 sn-p 中,我正在从用户那里搜索正确的“名称”,是否有任何违反“i”名称的东西? (例如 i.name 或当前客户端与其名称之间的某种连接)。

ChatServer 有问题的部分

public void sendPrivate(String message) throws Exception {
    Iterator<Socket> i = clients.iterator();

    StringTokenizer st = new StringTokenizer(message.substring(7,message.length()),", ");

     String realMessage = st.nextToken();                   
     String to = st.nextToken();
    while (i.hasNext()) {
        Socket socket = (Socket) i.next();
        try {
            if (name.equals(to)){
                DataOutputStream out = new DataOutputStream(socket.getOutputStream()); // create output stream for sending messages to the client
                out.writeUTF(realMessage); // send message to the client
            }
        }
        catch (Exception e) {
            System.err.println("[system] could not send message to a client");
            e.printStackTrace(System.err);
        }
    }
}

用户输入“姓名”的聊天客户端部分

public class ChatClient extends Thread
{
    public String name;
    protected int serverPort = 8888;

public static void main(String[] args) throws Exception {
    new ChatClient();
}

public ChatClient() throws Exception {
    Socket socket = null;
    DataInputStream in = null;
    DataOutputStream out = null;

    //whitelistaned
    String[] whitelist = {"Bob", "Frank", "Goliath", "Zealot", "Bruce Wayne"};
    int aliUstrezas = 0;

    //common courtesy
    System.out.println();
    System.out.println("Would you fancy in telling me your name, sir ?");
    System.out.println("Current whitelist: {'Bob', 'Frank', 'Goliath', 'Zealot', 'Bruce Wayne'} ");

    Scanner sc = new Scanner(System.in);
    name = sc.nextLine();

【问题讨论】:

  • 能否提供确切的错误信息,请将其添加到问题本身中

标签: java java-io


【解决方案1】:

ChatServer 不会实例化ChatClient 类型的对象,因此name 是否为public 无关紧要,它不能神奇地从任意对象中读取变量。

【讨论】:

  • 此外,ChatServer 引用 ChatClient 对象并没有什么意义,因为它们在概念上应该位于不同的主机上。
  • @RobbyCornelissen 此外,它们可能已经在不同的 JVM 中运行 - Yay GW
  • 但是我怎么进去呢?
  • @Z3br3 通过套接字发送它,就像你的其他数据一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-31
  • 2011-03-22
  • 1970-01-01
  • 2011-10-08
  • 1970-01-01
  • 2019-05-29
相关资源
最近更新 更多