What is the purpose of a resource in a WebSocket URL? - websocket

Looking at the W3 spec on WebSockets, I see
var socket = new WebSocket('ws://game.example.com:12010/updates');
socket.onopen = function () {
setInterval(function() {
if (socket.bufferedAmount == 0)
socket.send(getUpdateData());
}, 50);
};
I understand that the socket services lives on port 12010 at game.example.com, but what is the purpose of the '/updates' resource in the URL? If the service lives at some port, what good will a resource do?

You can expose different logical WebSockets on the same port, using different URI's.
Lets take chat as an example. You could use the URI to determine the particular channel or chat room you want to join.
var socket = new WebSocket('ws://chat.example.com/games');
var socket = new WebSocket('ws://chat.example.com/movies');
var socket = new WebSocket('ws://chat.example.com/websockets');
You can also use query strings. Imagine a stock ticker:
var socket = new WebSocket('ws://www.example.com/ticker?code=MSFT');
var socket = new WebSocket('ws://www.example.com/ticker?code=GOOG');

Related

Red5 Websocket chat application support multiple chat rooms

Using Red5 and
https://github.com/Red5/red5-websocket-chat
I try to do a basic chat.
It works ok for a example channel
var socket = new WebSocket('ws://serverIP:80/chat', 'chat');
Is there any way to do something similar to chat rooms using Red5 Websocket chat?
An example I want to do from JavaScript is using URL:
var socketRoom1 = new WebSocket('ws://serverIP:80/chat/Room1', 'chat');
var socketRoom2 = new WebSocket('ws://serverIP:80/chat/Room2', 'chat');
...
var socketRoomN = new WebSocket('ws://serverIP:80/chat/RoomN', 'chat');
or using Protocol:
var socketRoom1 = new WebSocket('ws://serverIP:80/chat', 'Room1');
var socketRoom2 = new WebSocket('ws://serverIP:80/chat', 'Room2');
...
var socketRoomN = new WebSocket('ws://serverIP:80/chat', 'RoomN');
But I only can make it works in JavaScript with that:
var socket = new WebSocket('ws://serverIP:80/chat', 'chat');
Thanks for your time.
You are able to do this by integrating with the Red5 scopes and creating the new scopes as needed. Scopes are basically interchangeable with "rooms" or contexts. This endeavor will require that you learn at least at a basic level how the scopes work. You'll also need to modify / extend the listener to add/remove the scopes as needed and to route your messages.
https://github.com/Red5/red5-websocket-chat/blob/master/src/main/java/org/red5/demos/chat/WebSocketChatDataListener.java
Here's some additional reading regarding scopes / rooms:
http://ria101.wordpress.com/2010/03/09/red5-cabin-fever-advanced-scope-and-room-management/
http://gregoire.org/2009/04/07/on-demand-room-scope-creation/

Creating two separate websocket connections for send and receive on localhost

I am new to websockets.
It is expected to send data(any data) on the send websocket connection using some port(ex:8000) and the localhost should echo the same data to the browser using a different websocket connection through a different port(ex:9000).
I understand websocket supports full duplex communication on a single connection,but the above is the design to implement.
Question 1) Is the above design possible?
Question 2) If yes,how to create two websocket connections(one to send and one to receive) to a single localhost websocket server?
1) Yes.
2) Creating two separated websockets. They will be different objects though.
You could blend both objects in a composite object like this:
var compositeWebSocket = function(urlSend, urlReceive){
var me = {};
var wsSend = new WebSocket(urlSend);
var wsReceive = new WebSocket(urlReceive);
var open = 0;
wsSend.onopen = opening;
wsReceive.onopen = opening;
var opening = function(){
if(open == 2){
if(me.onopen)
me.onopen();
}
else
open++;
};
var closing = funcion(){
try{wsSend.close();}catch(){}
try{wsReceive.close();}catch(){}
if(me.onclose)
me.onclose();
}
me.send = wsSend.send;
wsReceive.onmessage = function(msg){
if(me.onmessage)
me.onmessage(msg);
}
return me;
}
(Whatch out, this code is not tested and it is just an idea)

Best practice for sending unrelated data from server to client over WebSocket connection(s)

I am currently working on a single page web app that has a growing number of real-time widgets concurrently requiring different datasources. My question is which approach is best for using WebSockets as the vehicle for this data:
Option 1: The client opens a single socket connection with the server, then uses an API similar to the following to subscribe/unsubscribe/get/post data:
var socket = new WebSocket([URL]);
socket.emit("subscribe", [OPTIONS]);
socket.emit("unsubscribe", [OPTIONS]);
socket.emit("get", [OPTIONS]);
socket.emit("post", [OPTIONS])
Option 2: The client opens a socket for every source of data it needs to run the widgets on the page. Keep in mind that there could be many widgets requiring many different sources of data. For example, it would look something like this:
var sock1 = new WebSocket([URL]);
var widget1 = new Widget1(sock1);
var sock2 = new WebSocket([URL]);
var widget2 = new Widget2(sock2);
var sock3 = new WebSocket([URL]);
var widget3 = new Widget3(sock3);
Any insight would be much appreciated.
Andy

socket io user connection added on every html page refresh?

I have a nodeJS application added with socket io and Express like this:
Server:
var storeEachSocket=[];
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
storeEachSocket.push(socket);
console.log(storeEachSocket.length);
var clients = io.sockets.clients(); //clients is an array
console.log(clients.length);
});
Client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
</script>
Currently there is only ONE html page served by the server.
I found that, after the socket connection was built between html and server(at this time storeEachSocket.length is 1 and clients.length is 1 ),and if I refresh this html page, both storeEachSocket.length and clients.length would be 2, indicating that there are 2 socket connection between this html and the server.I want to know is this normal? the first socket connection would not die out even if after I create the second socket connection?
And I also want to know, if I intend to track this user(html),what shall I do if there are two socket connections used by the one user?
Refreshing the page doesn't add new connection, it basically removes current connection and creates another new connection. I think you should add a listener to disconnect event and remove the socket in the array that has been disconnected. I also don't believe that io.sockets.clients() would return 2 after refreshing as I've tested it on my machine.
If you want to track users, you need to have a user ID and store it into a key/value pair collection. Then you can restrict a user to create 2 connections by checking the collection in thr authorization handler.
var storeEachSocket = {};
io.set('authorization', function(handshake, accept){
var user = handshake.query;
if(user.id in storeEachSocket)
accept('User already connected', false);
else
accept(null, true);
});
io.on('connection', function(socket){
var user = socket.handshake.query;
storeEachSocket[user.id] = socket;
});
io.on('disconnect', function(socket){
var user = socket.handshake.query;
delete storeEachSocket[user.id]
});

how to uniquely identify users in websocket?

I am confused on how to give each new person that connects to the websocket a unique identification that can only affect his own information on the server. the information on the websocket is broadcast-ed so everyone receives the information from the server. I am using socket io for this.
There is not really enough information to provided a answer tailored to your needs, however here is a common method of sharing session data with sockets using an express.js memory store.
var sio = require('socket.io'),
parseCookies = require('connect').utils.parseSignedCookies
// authorization for sockets
io.set('authorization', function (hsData, accept) {
//get the handshake data for the socket
if(hsData.headers.cookie) {
//parse the cookies from the handshake data
var cookies = parseCookies(cookie.parse(hsData.headers.cookie), "session secret"),
sid = cookies["session path"];
//load your session store and find the user
sessionStore.load(sid, function(err, session) {
hsData.user = session.user;
return accept(null, true);
});
} else {
return accept('No cookie transmitted.', false);
}
});
io.sockets.on('connection', function(socket){
//now the socket will have user data
var user = socket.handshake.user,
});
Take a look at Baloons.IO to look at some great source code where sessions and socket.io live in harmony using a redis store.
Hope this helps!

Resources