I am implementing a Jetty Websocket servlet. When the server receives a new connection, I want to send a message that will be read by websocket's onopen function. I want this message to be sent only during the open and not using the regular connection.SendMessage() function. Is it possible to do that? and how?
Asked
Active
Viewed 2.5k times
2 Answers
67
Don't forget the query string. It's valid in WebSocket url.
new Websocket('ws://yoursite.com/path?a=1&b=2&c=3')
Then you can easily parse this url on server side to retrieve the data.

Lewis
- 14,132
- 12
- 66
- 87
-
2ya but how do you parse the url on the server side? where is the url itself made available? – Chris Scott Aug 08 '17 at 10:13
-
2should probably also mention the option of a @PathParam... see [this answer](https://stackoverflow.com/questions/21559260/how-do-i-pass-a-parameter-to-the-onopen-method-with-jee7-websockets) – jl. Feb 11 '18 at 15:38
-
I found it! I consoled out the `req` from here: `wss.on('connection', (ctx, req) => {` and I saw this in the big list of parameters: ` url: '/?/resolution=1920x1080',` which was my query string i appended to the original url over on the client. – dmikester1 Jan 28 '23 at 01:02
23
There is no support for this in the protocol but you could fudge something yourself.
- When your server completes a handshake, store the initial message you want to deliver to a client.
- In your client's
onopen
function, send a "read initial message" request. - In your server, check that this client hasn't read its initial message; respond with the message; set a flag saying that the initial message has been sent.
- Your client and server are both now free to send other messages.

simonc
- 41,632
- 12
- 85
- 103
-
Thanks, I was wondering if I may have missed something when searching online. I'll follow the approach you have suggested. – DPD Aug 30 '12 at 08:42
-
It's ridiculous that this isn't in the protocol... but hey ho. The above sounds the most sensible given the situation. – Daniel Gerson Jul 18 '22 at 11:24