Understanding XSockets.NET pubsub: producing and consuming messages from JavaScript - javascript

Let's say I've the following sample code (JavaScript):
// Client A
var conn = new XSockets.WebSocket([wsUri]);
conn.on(XSockets.Events.open, function (clientInfo) {
conn.publish("some:channel", { text: "hello world" });
});
// Client B (subscriber)
var conn = new XSockets.WebSocket([wsUri]);
conn.on(XSockets.Events.open, function (clientInfo) {
conn.on("some:channel", function(message) {
// Subscription receives no message!
});
});
Client B never receives a message. Note that this is a sample code. You might think that I don't receive the message because Client B got connected after Client A sent the message, but in the actual code I'm publishing messages after both sockets are opened.
The server-side XSocketsController is working because I'm using it for server-sent notifications.
What am I doing wrong? Thank you in advance!

It looks like you have mixed up the pub/sub with the rpc, but I cant tell for sure if you do not post the server side code as well.
But what version are you using? 3.0.6 or 4.0?
Once I know the version and have the server side code I will edit this answer and add a working sample.
EDIT (added sample for 3.0.6):
Just wrote a very simple chat with pub/sub.
Controller
using XSockets.Core.Common.Socket.Event.Interface;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
namespace Demo
{
public class SampleController : XSocketController
{
/// <summary>
/// By overriding the onmessage method we get pub/sub
/// </summary>
/// <param name="textArgs"></param>
public override void OnMessage(ITextArgs textArgs)
{
//Will publish to all client that subscribes to the value of textArgs.#event
this.SendToAll(textArgs);
}
}
}
HTML/JavaScript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/XSockets.latest.min.js"></script>
<script>
var conn;
$(function() {
conn = new XSockets.WebSocket('ws://127.0.0.1:4502/Sample');
conn.onopen = function(ci) {
console.log('open', ci);
conn.on('say', function(d) {
$('div').prepend($('<p>').text(d.text));
});
}
$('input').on('keydown', function(e) {
if (e.keyCode == 13) {
conn.publish('say', { text: $(this).val() });
$(this).val('');
}
});
});
</script>
</head>
<body>
<input type="text" placeholder="type and hit enter to send..."/>
<div></div>
</body>
</html>
Regards
Uffe

Related

Applying SignalR to update gridview

So when using signalR. I followed this example and got it working on a test web form, where in I open 2 tabs of the same page and tested it out:
SignalR Tutorial
Now I tried to modify it a little bit and tried to have 1 page as a sender and another as a receiver,
Page with Button to send message:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var msg = $.connection.myHub1; //change MyHub1.cs should be in camel myHub
// Create a function that the hub can call to broadcast messages.
msg.client.broadcastMessage = function (name, message) {
// $("[id*=btnRefresh]").click();
};
// Start the connection.
$.connection.hub.start().done(function () {
function RefreshData() {
// Call the Send method on the hub.
msg.server.send('admin', 'Refresh Grid');
};
});
});
</script>
protected void btnSendMsg_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "SigalRFunction", "RefreshData()", true);
}
Page with gridview:
<asp:Button runat="server" ID="btnRefresh" OnClick="btnRefresh_Click" Style="display: none" />
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var msg = $.connection.myHub1; //change MyHub1.cs should be in camel myHub
// Create a function that the hub can call to broadcast messages.
msg.client.broadcastMessage = function (name, message) {
$("[id=btnRefresh]").click();
};
// Start the connection.
$.connection.hub.start().done(function () {
function RefreshData() {
// Call the Send method on the hub.
//msg.server.send('admin', 'Refresh Grid');
};
});
});
</script>
protected void btnRefresh_Click(object sender, EventArgs e)
{
grdview.DataSource = grdviewData();
grdview.DataBind();
}
My idea was every time a message is received, the grid view/page should should automatically refresh. The grdviewDatasource and Databind works i.e placed it in pageload.Sadly nothing happens.
script src="assets/js/app.min.js"></script>
<script src="assets/js/scripts.js"></script>
<script src="assets/js/custom.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.10.2.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
Let me start by saying that you can invoke the hub's method either from client-side or code-behind code. Since it is not clear which way you want I'll cover both.
Your hub, MyHub1 should define the Send method, which you are going to invoke when the button is clicked:
MyHub1.cs
public class MyHub1 : Hub
{
public void Send(string name, string message)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub1>();
hubContext.Clients.All.broadcastMessage(name, message);
}
}
Note that the Send method calls the broadcastMessage javascript function (to notify clients), which you should define in the Receiver. You should add any code necessary to refresh your grid inside that function.
Receiver.aspx
<script type="text/javascript">
$(function () {
var msg = $.connection.myHub1;
// Create a function that the hub can call to broadcast messages.
msg.client.broadcastMessage = function (name, message) {
console.log(name + ", " + message);
// do whatever you have to do to refresh the grid
};
// Start the connection.
$.connection.hub.start().done(function () {
});
});
</script>
The Sender contains the two buttons: btnSendMsg will invoke the hub's Send method from code-behind; btnSendMsg2 will perform the same invocation from javascript. You can pick either depending on your needs.
Sender.aspx
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSendMsg" runat="server" Text="Server-Side" OnClick="btnSendMsg_Click" />
<input type="button" id="btnSendMsg2" value="Client-Side" />
</div>
</form>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var msg = $.connection.myHub1;
// Start the connection.
$.connection.hub.start().done(function () {
$('#btnSendMsg2').click(function () {
// Call the Send method on the hub.
msg.server.send('admin', 'Refresh Grid');
});
});
});
</script>
Sender.aspx.cs
protected void btnSendMsg_Click(object sender, EventArgs e)
{
var myHub1 = new MyHub1();
myHub1.Send("admin", "Refresh Grid");
}
Last but not least, make sure both the sender and the receiver pages reference the necessary jQuery and SignalR scripts and the autogenerated SignalR hub script.

Socket.io in javascript gives NOT_RESOLVED error

I need to connect HTML website to node server chat application. HTML client side has some HTML files and javascript file.I need to connect socket.io chat server using javascript. So it needs to initialize socket.io port inside javascript.
I have created socket.io chat server in node.js using javascript it is working fine. And I need to call that node server using javascript client site.
It should initialize and socket server connect. It should able to emit and receive messages from the server site.
I have a socket.io backend service which is working fine. Because I test it with nodeJS client application. But I need it to use existing HTML web site which is not nodeJS
I have searched on google and can't find any website which is about connecting sockt.io using a javascript file. All tutorials are using nodeJS.
When I used
var io = require('socket.io').listen(server);
inside the javascript file and open HTML page in the browser, it throws an error.
This is my code, I got this from the internet I was trying to connect this implement my real code.
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
// socket.io specific code
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message(from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>
Error in the front end:
Uncaught ReferenceError: io is not defined
at chat-footer.html:10
This is my folder structure:
var io = require('socket.io').listen(server); should be on the server side. var socket=io(); should be in the client side javascript. If you are putting var io in the client side then you would get an error. Plus you need to link the socket io library in the <head> tag of the HTML: <script src='/socket.io/socket.io.js'></script>. If you do not have the library linked the io() function will not work. I hope that this solves your problem.
UPDATED
According to your code. You never defined the io(); function. You went ahead in the front end and said var socket = io.connect(). You never said what io is. What it should be is name a different variable var socket = io(); and then use var connector = io.connect().
SECOND UPDATE
If the html page is not being served from the nodejs backend, you will not be able to use socketio as it is not connected to a server. You need to serve the html page from the backend and use socketio on the same backend server.
I have resolved the error. The reason was I cannot add a socket.io reference directly because it's nodeJS script. So I added socket.io.js from nodeJS service library. By adding that my HTML page will directly refer running nodeJS server socket.io.js file.
This is my working and complete code to connect socket.io nodeJS server.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="http://localhost:8000/socket.io/socket.io.js"></script> // add this line
<script>
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message(from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>

Open a popup containing ASPX postback result

I have an ASPX page with many fields that generate PDF documents when I click an "export to PDF" button.
I'd now like to have a "print PDF" button in JavaScript that does something like this:
w = window.open(?);
w.print();
w.close();
where "?" will perform the same postback as my "export to PDF" button.
If you need to submit (postback) your form to new window you can try to change form target to fake, like:
var form = $("form");
form.attr("target", "__foo");
Submit a form.
form.submit();
And remove the target (setitmeout(,1) - pot the event in end of js "event-queue", in our case - after form submitting):
setTimeout(function () { form.removeAttr("target"); }, 1);
Also, before submit you can try to open window with __foo id for more styling, and the form will submitted (postback) in this window instead of a new one:
var wnd = window.open('', '__foo', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes');
But I have no idea how to handle the submitted window and catch the onload or jquery's ready event. If you can do it share the workaround please and call the wnd.print(); You can play with iframes inside this wnd and maybe you will find a solution.
Updated:
Try to have a look in this prototype [tested in Chrome]:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
function PrintResult() {
var wnd, checker, debug;
debug = true;
// create popup window
wnd = window.open('about:blank', '__foo', 'width=700,height=500,status=yes,resizable=yes,scrollbars=yes');
// create "watermark" __loading.
wnd.document.write("<h1 id='__loading'>Loading...</h1>");
// submit form to popup window
$("form").attr("target", "__foo");
setTimeout(function() { $("form").removeAttr("target"); }, 1);
if (debug)
{
$("#log").remove();
$("body").append($("<div id='log'/>"));
}
// check for watermark
checker =
setInterval(function () {
if (debug) $("#log").append('. ');
try {
if (wnd.closed) { clearInterval(checker); return; }
// if watermark is gone
if (wnd.document == undefined || wnd.document.getElementById("__loading") == undefined) {
if (debug) $("#log").append(' printing.');
//stop checker
clearInterval(checker);
// print the document
setTimeout(function() {
wnd.print();
wnd.close();
}, 100);
}
} catch (e) {
// ooops...
clearInterval(checker);
if (debug) $("#log").append(e);
}
}, 10);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="ReportButton" OnClick="ReportRenderClick" Text="Export to PDF" OnClientClick="PrintResult()"/>
<asp:Button runat="server" Text="Just a button."/>
</div>
</form>
</body>
</html>
And here is .cs file:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ReportRenderClick(object sender, EventArgs e)
{
Response.Clear();
Thread.Sleep(2000);
Response.ContentType = "application/pdf";
Response.WriteFile("d:\\1.pdf");
//Response.ContentType = "image/jpeg";
//Response.WriteFile("d:\\1.jpg");
//Response.Write("Hello!");
Response.End();
}
}
Open the pdf window with IFrame and you could do this:
Parent Frame content
<script>
window.onload=function() {
window.frames["pdf"].focus();
window.frames["pdf"].print();
}
</script>
<iframe name="pdf" src="url/to/pdf/generation"></iframe>
Inspired from this https://stackoverflow.com/a/9616706
In your question tag you have the asp.net tag, so I guess you have access to some kind of ASP.NET server technology.
I would suggest to do it like this:
Create a HttpHandler or an ASP.NET MVC action that returns a FileContentResult
In your page, use this code to download and print the file (actually found it here, pasting it for future reference!)
Click here to download the printable version
There are some good tutorials on writing the server side:
Walkthrough: Creating a Synchronous HTTP Handler
How to get particular image from the database?
And one of my own: Download PDF file from Web location and Prompt user SaveAs box on client in web-Application ASP C#

Getting error in establishing a cross-domain connection using SignalR 2.0

When I am going to use it's for cross domain then i am getting error message when i call start() function. Error in jquery.signalR-2.0.2.min.js.
Error message is
"Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. ."
I am using server side code
Startup.cs class code is:
[assembly: OwinStartup(typeof(SignalRNew.Startup))]
namespace SignalRNew
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
}
}
}
I am using client side script is:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-2.0.2.min.js"></script>
</head>
<body>
<div></div>
<script type="text/javascript">
$.connection.hub.url = 'http:\\localhost:2100\signalr';
$.connection.hub.start().done(function () {
alert('Now connected');
});
</script>
</body>
</html>
kindly reply...
Try to enable the logging in the client side, and look for error messages or warnings:
http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#logging
Enable logging (with the generated proxy)
$.connection.hub.logging = true;
$.connection.hub.start();
Enable logging (without the generated proxy)
var connection = $.hubConnection();
connection.logging = true;
connection.start();
Please try creating the proxy by following steps.
var connection=$.hubConnection();
var proxy=connection.createHubProxy("hubName");
connection.start().done(function () {
alert('Now connected');
});
You have connected the url without giving the hub name .That may be the problem.

could not open db , $ is not defined, Failed to load jquery

The error is that the db could not be opened and $ not defined, failed to load resources(j query).The code aims at receiving the input field values(date,cal) and storing them into the database using indexedDB
<!DOCTYPE html>
<html manifest="manifest.webapp" lang="en">
<head>
<meta charset="utf-8">
<title>Diab</title>
<link rel="stylesheet" href="diab.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0/jquery.min.js"></script>
<script type="text/javascript" src="diab1.js"></script>
</head>
<body>
<input type="date" id="date">Date</input>
<input type="number" id="cal">Cal</input>
<button id="add" >Add</button>
</body>
</html>
(function()
{ var db;
var openDb=function()
{
var request=indexedDB.open("diabetore");
request.onsuccess = function()
{
console.log("DB created succcessfully");
db = request.result;
console.log("openDB done!!");
};
request.onerror=function(){
alert("could not open db");
};
request.onupgradeneeded = function()
{
console.log("openDB.onupgradeneeded function");
var store = db.createObjectStore("diab", {keyPath: "date"});
var dateIndex = store.createIndex("date", "date",{unique: true});
// Populate with initial data.
store.put({date: "june 1 2013",cal:70});
store.put({date: "june 2 2013",cal:71});
store.put({date: "june 3 2013",cal:72});
store.put({date: "june 8 2013",cal:73});
};
};
function getObjectStore(store_name,mode)
{
var tx=db.transaction(store_name,mode);
return tx.objectStore(store_name);
}
function addItems(date,cal)
{
console.log("addition to db started");
var obj={date:date,cal:cal};
var store=getObjectStore("diab",'readwrite');
var req;
try
{
req=store.add(obj);
}catch(e)
{
if(e.name=='DataCloneError')
alert("This engine doesn't know how to clone");
throw(e);
}
req.onsuccess=function(evt)
{
console.log("****Insertion in DB successful!!****");
};
req.onerror=function(evt)
{
console.log("Could not insert into DB");
};
}
function addEventListners()
{
console.log("addEventListeners called...");
$('#add').click(function(evt){
console.log("add...");
var date=$('#date').val();
var cal=$('#cal').val();
if(!date || !cal)
{
alert("required field missing..");
return;
}
addItems(date,cal);
});
}
openDb();
addEventListners();
})();
Regarding the problem of not being able to see the db created, when you open the database you should pass another parameter with the version of the database, like:
var request=indexedDB.open("diabetore",1);
To see the DB structure on the Resources tab of Chrome Developer Tools, sometimes you must refresh the page.
You will also have a problem with your addEventListners() function since your anonymous function is run before the browser reads the HTML content so the browser doesn't not know about the '#add' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function() {
var db;
var openDb=function() {
You should test the script URL in your browser. Then you'd realize that the script doesn't exist.
You need to change 2.0 to 2.0.0 for example.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

Categories

Resources