I have a scenario which I need to create a very simple text chat using nodejs
and Websocket
.
I have everything set up and working.
I now need to allow users to send a parameter in the websocket connection
URL.
Like so: websocket = new WebSocket("ws://test-website.net:8080/?id=55");
in my reserach I came across quite a few similar questions and found out that I can pass the parameters in the URL like the example above.
However, none of them mentions or explains how to get this parameter (55 in this example) in server.js
wss.on('connection', function(ws) {
///I need to get the parameter here////
});
Could someone please advice on this issue?
Thanks in advance.
To create a WebSocket and open the connection to FME Server use getWebSocketConnection method. The result is an open WebSocket you can use in your application to communicate with FME Server. This example sends a basic JSON object as a string to the server, and displays the response from the server.
To send a message through the WebSocket connection you call the send() method on your WebSocket instance; passing in the data you want to transfer. socket. send(data); You can send both text and binary data through a WebSocket.
The Message event takes place usually when the server sends some data. Messages sent by the server to the client can include plain text messages, binary data, or images. Whenever data is sent, the onmessage function is fired.
In your websocket request handler, it is normally passed the web socket as the first argument; the incoming HTTP request is passed as a second argument:
webSocketServer.on('connection', function connection(ws_client_stream, incoming_request) {
console.log(incoming_request.url);
});
From there, you can use url.parse
to get the components of the URL, such as the query string that you are interested in.
For websocket library in nodejs (websocket.js npm) :
wsServer.on('request', function(request){
var FullURL = request.resourceURL.query;
console.log(FullURL);
// . . your code . . //
}
link = wss://localhost/?param=value
output
{ param : 'value' }
here request.resourceURL retuen a object
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?id=65&encoding=text',
query: { id: '65', encoding: 'text' },
pathname: '/',
path: '/?id=65&encoding=text',
href: '/?id=65&encoding=text' }
If you're using 'websocket' lib, the following code retrieves your queryStrings:
wsServer.on('request', function(request)
{
console.log(request.resourceURL.query);
}
Note 1: You don't need to parse anything here.
Note 2: Though it has been answered years ago, this answer goes to those in case where people find the above-mentioned answer more complicated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With