开发者

Sending messages to specific threads/users in instant messaging app

开发者 https://www.devze.com 2023-01-13 16:38 出处:网络
I\'m currently writing an IM server in Java for a web-based chat application using the new WebSocket protocol.The server currently listens for connections and creates a new thread for each connecting

I'm currently writing an IM server in Java for a web-based chat application using the new WebSocket protocol. The server currently listens for connections and creates a new thread for each connecting client that handles input and out开发者_C百科put. 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.

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. I just need a push in the right direction.

Thanks!


I don't think you should re-invent the wheel, try using JGroups for chat implementation


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消