one server multiple clients

后端 未结 4 2022
小鲜肉
小鲜肉 2021-01-22 08:57

I am engaging the following problems:

  1. I need to write a server program, will accept multiple clients
  2. all clients are subscribing the same data from server
相关标签:
4条回答
  • 2021-01-22 09:16

    is it necessary to have a thread for each client socket?

    No, as a matter of fact, I wouldn't even not recommend it. If it's a small project and you don't want to use any existing library, I would suggest you use the java.nio package and the SelectableChannels. With a so called selector you can easily monitor clients for incoming data in a non-blocking way.

    Here are a few useful links:

    • NIO Examples (from the official tutorial)
    • The Rox Java NIO Tutorial
    0 讨论(0)
  • 2021-01-22 09:29

    Thanks BTW: sorry for confusing every one, it is a small project that only involve 5-10 classes.

    There's definately nothing wrong with it. All higher level abstractions are based on sockets one way or another. Unless your project is sufficiently large there is no need to pull a series other frameworks/toolkit to perform the same job. Threads are cheap (and can even benefit from a multicore architecture), although using SelectableChannels as @aioobe suggested is not a bad idea either.

    When your projects require it, you can always learn about other inter-process communication methods (message passing, remote method invocaton etc., and its about 100 implementations) then.

    You might however want to limit the number of threads you server use simultaneously. This can easily be achieved by claiming e.g., a semaphore of a size equal to the number of threads you want to serve. Another interesting thing to consider is using java thread pools to better reuse your resources.

    0 讨论(0)
  • 2021-01-22 09:30

    What about using standards technology for solving this problem?

    JMS topic A distribution mechanism for publishing messages that are delivered to multiple subscribers.

    Tutorial

    0 讨论(0)
  • 2021-01-22 09:31

    Others have mentioned that you can use the nio library to reduce the number of threads necessary. i just wanted to point out that your current example code will not work. you must use a thread per socket when using the standard io streams. the available() method is pretty much useless (in general) and will not stop your control thread from blocking.

    0 讨论(0)
提交回复
热议问题