HTML 5 Web Sockets channels routing - javascript

I need to create Web Socket client connection in format ws://host:port/route to be able listen socket messages only from this route and not be able to listen them from, for example ws://host:port/.
Now I got a code like this, but it does not work properly:
Client side:
var ws = new WebSocket("ws://localhost:5678/test");
ws.onopen = function () {
console.log("Connected!");
};
ws.onmessage = function (e) {
console.log(e);
};
Server side:
if __name__ == '__main__':
ServerFactory = BroadcastServerFactory
factory = ServerFactory(u"ws://localhost:5678/test")
factory.protocol = BroadcastServerProtocol
listenWS(factory)
reactor.run()
But i'm still able to listen messages from ws://localhost:5678.
Are there any mechanism to make Web Sockets routing or dividing them by channels?

Related

How to use websocket on client side?

When one user adds an event using API, other users should get an alert about new event
Is it possible to:
send message from client-side when one user adds an event using wss://echo.websocket.org
let socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = () => socket.send('New event');
and get this message from other browser?
let socket = new WebSocket('wss://echo.websocket.org');
socket.onmessage = function(event) {
var message = event.data;
alert(message)
};
server-side on PHP
Is there any source based on "How to realize WebSocket server ( PHP )"?
I don't want to send request to server every some inetrval for checking updates, is there any wat to keep connection alive and when got response show alert to the client?

WCF Full Duplex Application with Websocket Client

We had created WCF web service with one method. Service is hosted on external server i.e. Windows Server 2012 and IIS 8.0.
WCF Service URL: http://184.106.9.214/WCFReportingService/Service1.svc
WCF method:
public void ProcessReport()
{
for (int i = 1; i <= 100; i++)
{
// some logic to process the report
Thread.Sleep(100);
// Get the callback channel to send messages to the client
OperationContext.Current.
GetCallbackChannel<IReportServiceCallback>().Progress(i);
}
}
We are trying to create client using HTML5 and JavaScript. Below is the logic we used to initiate the connection.
ws = new WebSocket("ws://localhost/WCFReportService/Service1.svc");
alert(ws);
ws.onopen = function () {
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
$("#spanStatus").text("connected");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
$("#spanStatus").text(evt.data);
};
ws.onerror = function (evt) {
$("#spanStatus").text(evt.message);
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
$("#spanStatus").text("disconnected");
};
We were not able to establish the connection to server. We are thinking that it might be something to do with client side web.config file. But we are not sure how to implement or build connection.
Can anyone help us to build client-server connection?
Thanks.
It might help someone with similar problem I had. Below are the links I used and I was able to get it working.
Introduction 2 : http://www.codeproject.com/Articles/618032/Using-WebSocket-in-NET-4-5-Part-2
Introduction 3 : http://www.codeproject.com/Articles/619343/Using-WebSocket-in-NET-4-5-Part-3

Websockets in python and js

I am currently creating a website and I'm totally confused about Websockets.
I have some data in a database that is shown on my website. Now every once in a while there are new entries in the database, which should be shown on the website without reloading it, now I thought this could somehow be achieved using websockets.
I'm using web.py as framework for my website, and I use AngularJS.
In my app.py, I recieve the database entries and return them as JSON.
In js I want to receive the JSON message and save it in the $scope, which then gets "printed" on the website using AngularJS and I created a client side WebSocket for it like this:
var app = angular.module('web');
app.factory('runservice', function() {
var service = {};
service.connect = function() {
if(service.ws) { return; }
var ws = new WebSocket('wss://localhost:8080');
ws.onopen = function() {
service.callback("Success");
};
ws.onerror = function(evt) {
service.callback("Error: " + evt.data);
}
ws.onmessage = function(message) {
service.callback(message.data);
};
service.ws = ws;
}
service.subscribe = function(callback) {
service.callback = callback;
}
return service;
});
app.controller('runController', function($scope, runservice) {
runservice.connect();
runservice.subscribe(function(message) {
var data = JSON.parse(message);
$scope.runs = data;
});
});
Now, do I need a server side socket in my app.py or something else? If so, can anyone provide an example how I'd achieve this in web.py?
You definitely need to have websocket code on your server, or else your client isn't keeping a connection alive with your server and vice versa.
If your wish is to make use of realtime websockets, then this package for your web.py application server https://github.com/songdi/webpy-socketio will be very useful, as will this for you angular client application https://github.com/btford/angular-socket-io
Another option would be to simply long poll your server. AKA make asynchronous requests every ~10 seconds or so to your application and retrieve only the newest entries.
I hope this is of some help!

Emit Events To Socket.IO Not Working From Server

i am trying to get a chat program to work using socket.io but it doesnt seem to work properly.
i am using a Node.js server and it seems to be running properly. i think this may have something to do with emitting to rooms.
the code i have on the client browser is:
<script>
var socket = io("https://localhost:3000/userChat");
socket.on('connect', function(){
socket.emit('initialiseConnection', "user1");
});
socket.on('messageIn', function(msg){
console.log(msg);
$('#messages').append($('<li>').text(msg.message));
});
</script>
so when the page loads, socket.io it connects to the server and emits the "initialiseConnection" event on the server with "user1". which is a new room specifically for that user.
on the server, the code i have handling "initialiseConnection" is:
socket.on("initialiseConnection", function(username){
socket.join(username);
console.log(username + " has joined.");
Message.find({recipient:username}, function (err, message){
console.log("messages for "+username+": "+message.length);
for (var x = 0; x < message.length; x++){
console.log(username+"'s message "+x);
console.log(message[x]);
socket.to(username).emit("messageIn", {"message":message[x]});
}
});
});
this code as you can see, creates and joins a room with the same name as the username. the looks in the database for any messages, and tries to emit those messages to the user. i log the message. there is definately a message and the username in the "socket.to()" method is also correctly shown in the logs. but the "socket.on('messageIn')" on the client browser doesnt seem to be picking up the event.
i have also tried putting:
setTimeout(function() {
socket.to(username).emit("messageIn", {"message":"test message"});
}, 5000);
immediately after the socket.join(), in case this was related to some backbround processing that needed to complete
can anyone see where i may have gone wrong on this?
Thanks.
--EDIT 1--------------------------------------
var https = require('https');
var express = require('express');
var app = express();
var server = https.createServer(https_options, app).listen(3000);
var io = require('socket.io')(server);
var userChat = io.of("/userChat");
userChat.on('connection', function(socket){
console.log('a user connected');
socket.on("initialiseConnection", function(username){
...
});
socket.on('disconnect', function(){
socket.leave(socket.room);
});
});
You need to change this:
socket.to(username).emit("messageIn", {"message":message[x]});
to this:
socket.emit("messageIn", {"message":message[x]});
A socket is the endpoint. When sending, you just send directly to the socket. You don't send to a user in a room? You just send to a socket. Since you already have the socket in your socket variable, that's what you send to.

Listening websocket in MVC

I'm using MVC 4. I have a js code that needs to communicate with the server with the help of Websockets. I'm using Fleck at the server. I'm creating the socket server in Application_Start event. But when I try the connection from browser console, I get errors like Connection refused.
Here is my global.asax code.
protected void Application_Start()
{
IPAddress ip = null;
if (GetResolvedConnecionIPAddress(out ip)) // Get host ip
{
string Domain = "wss" + System.Uri.SchemeDelimiter + ip + ":" + "8092";
FleckLog.Level = Fleck.LogLevel.Debug;
try
{
if (GetResolvedConnecionIPAddress(out ip))
{
var server = new WebSocketServer(Domain);
server.Start(socket =>
{
LogWriter.Logger.Info("WS: Inside socket server");
socket.OnOpen = () =>
{
LogWriter.Logger.Info("WS: OnOpen socket");
};
socket.OnClose = () =>
{
LogWriter.Logger.Info("WS: OnClose socket");
};
socket.OnMessage = message =>
{
LogWriter.Logger.Info("WS: OnMsg socket");
};
});
}
}
catch (Exception e)
{
throw;
}
}
}
It looks like as soon as the Application_Start method ends, that WebSocketServer is going to get out of scope and eventually garbage collected.
You could, set that object as member in the Global class, and dispose it on the Application_End event for example.
UPDATE:
You are also using the wss schema but not providing any certificate configuration. Please note that IIS and Fleck are two different things, that runs in different ports, and not because you create Fleck into the ASP.NET app means that Fleck is going to infer the SSL/TLS configuration or any configuration at all. Try to set the schema to ws instead and open the page without HTTPS and see if it works.

Categories

Resources