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)
Related
I am writing some websocket code and I have this so far:
window.onload = function() {
// Get references to elements on the page.
var form = document.getElementById('message-form');
var messageField = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');
var socket = new WebSocket('ws://echo.websocket.org');
// Show a connected message when the WebSocket is opened.
socket.onopen = function(event) {
socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.url;
socketStatus.className = 'open';
};
// Handle any errors that occur.
socket.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
form.onsubmit = function(e) {
e.preventDefault();
// Retrieve the message from the textarea.
var message = messageField.value;
// Send the message through the WebSocket.
socket.send(message);
// Add the message to the messages list.
messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message +
'</li>';
// Clear out the message field.
messageField.value = '';
return false;
};
socket.onmessage = function(event) {
var message = event.data;
messagesList.innerHTML += '<li class="received"><span>Received:</span>' +
message + '</li>';
};
closeBtn.onclick = function(e) {
e.preventDefault();
// Close the WebSocket.
socket.close();
return false;
};
socket.onclose = function(event) {
socketStatus.innerHTML = 'Disconnected from WebSocket.';
socketStatus.className = 'closed';
};
};
What is this code doing:
var socket = new WebSocket('ws://echo.websocket.org');
What url is that? When I visit there with my browser it does not exist but it seems to be important as I can't simply jus replace that url with random strings. What does it do? Is Websocket an external API?
I'm looking at the network tab and I see this:
Request URL: ws://echo.websocket.org/
Request Method: GET
Status Code: 101 Web Socket Protocol Handshake
conceptually, what is going on? Why do I need to make a request to an external site to use Websockets?
echo.websocket.org provides a webSocket server that lets you make a webSocket connection to it and then it simply echos back to you anything that you send it. It's there primarily for testing and demo purposes.
The code you show looks like a demo/testing app designed to run in a browser web page for a webSocket connection which you can access something similar here: https://websocket.org/echo.html.
A URL starting with ws:// indicates a connection that intends to use the webSocket protocol.
What is this code doing:
var socket = new WebSocket('ws://echo.websocket.org');
It is making a webSocket connection to a webSocket server at echo.websocket.org.
What url is that?
That is a webSocket URL that indicates the intent to use the webSocket protocol to connect and talk to that host. This is not something you type in the URL bar of a browser. It's something that is used by a programming language (such as Javascript in your browser).
Is Websocket an external API?
It's a protocol that specifies a means of connecting, a security scheme, a packet data format, etc... You could say that the http protocol is to the webSocket protocol as the English language is to Japanese. They are different means of communicating. The specification for the webSocket protocol is here: https://www.rfc-editor.org/rfc/rfc6455.
It's also designed to fit well into the http/browser world and to be friendly with infrastructure that was originally designed for http requests. Just searching for "what is websocket" on Google will turn up all sorts of descriptive articles. The Wikipedia page for webSocket provides a pretty good overview.
There is tons written on the web about what the webSocket protocol is and is useful for so I won't repeat that here. You can see a tutorial on webSocket clients here and a tutorial on webSocket servers here.
In a nutshell, it's designed to be a long lasting, continuous connection (supported in all modern browsers) that allows a client to connect to a server and then maintain a continuous connection for (potentially) a long duration. While that connection is open, data can be easily sent both ways over the webSocket. The primary reason people use it is when they want the server to be able to send data directly to the client in a timely fashion without making the client continuously ask the server over and over again if it has any new data. Once a webSocket connection is established, the server can just "push" data to the client at any time.
I'm looking at the network tab and I see this. Conceptually, what is going on?
Request URL: ws://echo.websocket.org/
Request Method: GET Status Code:
101 Web Socket Protocol Handshake
Those are the first steps of establishing a webSocket connection. You can see a more complete description of how that connection works here: How socket.io works. That post talks about socket.io which is another layer built on top of webSocket, but the underlying protocol is webSocket.
Why do I need to make a request to an external site to use Websockets?
A webSocket's purpose is to connect a client to a server (so data can then be sent between them) so it would only be used when connecting to some server somewhere.
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/
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
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]
});
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');