简体   繁体   English

将消息发送到即时消息传递应用程序中的特定线程/用户

[英]Sending messages to specific threads/users in instant messaging app

I'm currently writing an IM server in Java for a web-based chat application using the new WebSocket protocol. 我目前正在使用新的WebSocket协议用Java为基于Web的聊天应用程序编写IM服务器。 The server currently listens for connections and creates a new thread for each connecting client that handles input and output. 服务器当前正在监听连接,并为每个处理输入和输出的连接客户端创建一个新线程。 However, I cannot figure out how I'd go about sending messages between specific threads. 但是,我无法弄清楚如何在特定线程之间发送消息。

I've set it to where the web-based client sends the users ID to the server and that ID is used as the thread name using currentThread.setName() but I'm not sure where to go from there. 我已经将其设置为基于Web的客户端将用户ID发送到服务器的位置,并且使用currentThread.setName()将该ID用作线程名,但是我不确定从那里开始。

I'm only about 3 weeks into Java so the answer to my question may be ridiculously simple or I may be going about this whole thing completely wrong. 我到Java仅仅只有3周的时间,所以我的问题的答案可能非常简单,或者我可能会完全错失整个问题。 I just need a push in the right direction. 我只需要向正确的方向推进即可。

Thanks! 谢谢!

我不认为您应该重新发明轮子,尝试使用JGroups进行聊天

What kind of messages do you want to send? 您想发送什么样的消息? One thing that you could try is storing your Threads in a List that all your Threads can access, searching for the Thread that you want to send the message to, then calling a method on the thread: 您可以尝试做的一件事是将线程存储在所有线程都可以访问的列表中,搜索要向其发送消息的线程,然后在线程上调用方法:

class MyThread extends Thread{
  private static List<MyThread> chatClients;

  public void run(){
    for (MyThread t : chatClients){
      if (...){
        t.sendMessage(...);
      }
    }
    //...
  }

  public void sendMessage(...){
    //...
  }
}

Also note that, because you are dealing with threads, you must keep synchronization in mind. 另请注意,由于您正在处理线程,因此必须牢记同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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