Reputation: 137
I'm using org.eclipse.jetty.websocketclient and I want to open multiple web sockets to different URLs. I'm working with Java.
How do I need to do that? I want to open the web sockets in multiple threads. 1. Do I need to create websocketclient for each connection? 2. Can I use any websocketclient factory? Is there any? 3. Do I need to open only one websocketclient, keep it opened and open somehow web sockets with it? 4. What is wrong with creating multiple websocket clients?
Upvotes: 1
Views: 2251
Reputation: 49515
This answer talks about Jetty 9 WebSockets.
you have 1 WebSocketClient
, think of it as a Browser, with each call to connect()
establishing a new connection.
Each call to connect()
should have a new WebSocket instance, each instance will be managed by the WebSocketClient's Executor
causing in essence each websocket instance to be on its own thread.
Followup Answers
Ideally, have only 1 WebSocketClient, and start it only once. leave it started for the time period where you have active websocket connections. Stop the WebSocketClient when there are no more connections.
Generally speaking, avoid reusing objects for multiple requests, unless you know what you are doing. Example: the ClientUpgradeRequest and URI, are associated with the WebSocket Session, which if reused across multiple connections, will have a state change on close of the first connection, making the data invalid for the other connections, then there is also the Garbage collection references that make cleaning up the old connections difficult until all connections are closed.
You can call connect()
concurrently, go for it. Each connection attempt is processed based on the Executor behavior (eg: if you have a single threaded Executor, then only 1 connect occurs at a time)
Creating a new WebSocketClient for every connect is excessively wasteful of resources. It would be like starting an entire WebServer for each incoming request. A WebSocketClient manages the selectors, threading, session tracking, etc. I realize where you are coming from, with older http client libraries having this behavior, but even those http clients are updating themselves to this new browser-ish model thanks to spdy and http/2.
Upvotes: 2