Java websocket creates new Instance with each client connection with server - javascript

I am using Java to create WebSocket Server And Javascript and HTML for the Client. The server starts successfully and can accept connection from WebSocket clients, But it is creating a new instance of the server every time a client connects.
Code of Server:-
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/websocketendpoint")
public class WsServer {
Set<Session> sessions = new HashSet<Session>();
int count = 0;
#OnOpen
public void onOpen(Session session){
System.out.println("Open Connection ...");
count+=1;
System.out.println(count); //On the logcat it shows only 1
sessions.add(session);
for(Session s: sessions)
{
System.out.println(s); //On the logcat it shows only session
}
}
#OnClose
public void onClose(){
System.out.println("Close Connection ...");
}
#OnMessage
public String onMessage(String message){
System.out.println("Message from the client: " + message);
String echoMsg = "Echo from the server : " + message;
return echoMsg;
}
#OnError
public void onError(Throwable e){
e.printStackTrace();
}
}
Code Of Client:-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</title>
</head>
<body>
<form>
<input id="message" type="text">
<input onclick="wsSendMessage();" value="Echo" type="button">
<input onclick="wsCloseConnection();" value="Disconnect" type="button">
</form>
<br>
<textarea id="echoText" rows="5" cols="30"></textarea>
<script type="text/javascript">
var webSocket = new WebSocket("ws://192.168.225.26:8080/WebSocketServerExample/websocketendpoint");
var echoText = document.getElementById("echoText");
echoText.value = "";
var message = document.getElementById("message");
webSocket.onopen = function(message){ wsOpen(message);};
webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ wsClose(message);};
webSocket.onerror = function(message){ wsError(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Message sended to the server : " + message.value + "\n";
message.value = "";
}
function wsCloseConnection(){
webSocket.close();
}
function wsGetMessage(message){
echoText.value += "Message received from to the server : " + message.data + "\n";
}
function wsClose(message){
echoText.value += "Disconnect ... \n";
}
function wserror(message){
echoText.value += "Error ... \n";
}
</script>
</body>
</html>
And after the 2nd client connects it only shows 1 as a count and there is only one session is stored on the Set.
Technologies I am using:-
Tomcat v9.0
Eclipse Java EE IDE
Java For Server And JavaScript For Client
javax.websocket for WebSocket.
My question is how can we stop this and make clients connect to only one instance?

Look at the method names of WsServer. It is only intended for one client because the functions don't send a connection id with them. So make your counter static or move it to an other class.

that is the default behaviour.
Try adding #Singleton annotation before #ServerEndpoint.

Related

How not update the value from the browser when using jquery in Ajax?

I have a problem on my code. I want my value from the URL on Ajax call not to update twice, but once only. But what the code does it keeps on updating that field from the URL and do mismatch between 0 and 1 value from the URL on Ajax call. Please see my logic on this code and help me to improve my logic. I only want my field8=1 update once only on BtnOn() function, so if i click twice without refreshing the page it does not, same applies with BtnOff() function. That keeps that original value to its state as being field8=0. So it wont do mismatched between field8=1 to it, which is doing that currently which is bad to a user to see it and also status message as well.
<div class ="success"></div>
<div class = "warning"></div>
<div class="col-md-2 text-center">
<button id="singlebutton" name="singlebutton" class="btn btn-danger"
onclick="BtnOff();">Off</button> <br>
</div>
<!------
---->
<br/>
<div class = "col-md-2 text-center">
<button id = "singlebtn" name="singlebtn" class="btn btn-success"
onclick = "BtnOn();">On</button> <br>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var data;
function BtnOff() {
$.ajax({
url:'https://api.thingspeak.com/update api_key=D***&field8=0',
type:'GET',
data:{
type:'text'
},
success:function(response){
alert(response);
$('div.warning').html('status changed to zero').delay(1000).fadeOut();
$('#singlebutton').append(data);
return false;
}
});
//setTimeout("Subscribe()", 100);
}
// second button to unsubscribe.
function BtnOn() {
$.ajax({
url:'https://api.thingspeak.com/updateapi_key=D***&field8=1',
type:'GET',
data:{
type:'text'
},
success:function(response){
alert(response);
$('div.success').html('status changed to one').delay(1000).fadeOut();
$('#singlebtn').append(data);
return data;
}
});
var h = setTimeout("Subscribe()", 100);
clearTimeout(h);
}
</script>
<!-- Back End--->
/*
Azure IoT Hub WiFi
This sketch securely connects to an Azure IoT Hub using MQTT over WiFi.
It uses a private key stored in the ATECC508A and a self signed public
certificate for SSL/TLS authetication.
It publishes a message every 5 seconds to "devices/{deviceId}/messages/events/" topic
and subscribes to messages on the "devices/{deviceId}/messages/devicebound/#"
topic.
The circuit:
- Arduino MKR WiFi 1010 or MKR1000
This example code is in the public domain.
*/
#include <Wire.h>
#include <Arduino_MKRENV.h>
#include <SPI.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h> // change to #include <WiFi101.h> for MKR1000
#include "arduino_secrets.h"
/////// Enter your sensitive data in arduino_secrets.h
const char ssid[] = SECRET_SSID;
const char pass[] = SECRET_PASS;
const char broker[] = SECRET_BROKER;
String deviceId = SECRET_DEVICE_ID;
String mqttPassword = SECRET_MQTT_PASSWORD;
WiFiClient wifiClient; // Used for the TCP socket connection
BearSSLClient sslClient(wifiClient); // Used for SSL/TLS connection, integrates with ECC508
MqttClient mqttClient(sslClient);
unsigned long lastMillis = 0;
unsigned long postNumbers = 0;
float temperature, humidity, pressure, illuminance, uva, uvb, uvIndex;
String jsonString = "";
void setup()
{
Serial.begin(9600);
while (!Serial);
if (!ENV.begin())
{
Serial.println("Failed to initialize MKR ENV shield!");
while (1);
}
if (!ECCX08.begin())
{
Serial.println("No ECCX08 present!");
while (1);
}
// reconstruct the self signed cert
ECCX08SelfSignedCert.beginReconstruction(0, 8);
ECCX08SelfSignedCert.setCommonName(ECCX08.serialNumber());
ECCX08SelfSignedCert.endReconstruction();
// Set a callback to get the current time
// used to validate the servers certificate
ArduinoBearSSL.onGetTime(getTime);
// Set the ECCX08 slot to use for the private key
// and the accompanying public certificate for it
sslClient.setEccSlot(0, ECCX08SelfSignedCert.bytes(), ECCX08SelfSignedCert.length());
// Set the client id used for MQTT as the device id
mqttClient.setId(deviceId);
// Set the username to "<broker>/<device id>/api-version=2018-06-30" and empty password
String username;
username += broker;
username += "/";
username += deviceId;
username += "/api-version=2018-06-30";
mqttClient.setUsernamePassword("MKR1010", mqttPassword);
// Set the message callback, this function is
// called when the MQTTClient receives a message
mqttClient.onMessage(onMessageReceived);
}
void loop()
{
if (WiFi.status() != WL_CONNECTED)
{
connectWiFi();
}
if (!mqttClient.connected())
{
// MQTT client is disconnected, connect
connectMQTT();
}
// poll for new MQTT messages and send keep alives
mqttClient.poll();
// publish a message roughly every 60 seconds.
if (millis() - lastMillis > 60000)
{
lastMillis = millis();
publishMessage();
readEnvSensors();
}
}
void readEnvSensors()
{
// read all the sensor values
temperature = ENV.readTemperature();
humidity = ENV.readHumidity();
pressure = ENV.readPressure();
illuminance = ENV.readIlluminance();
uva = ENV.readUVA();
uvb = ENV.readUVB();
uvIndex = ENV.readUVIndex();
postNumbers++;
Serial.print("Post number: ");
Serial.println(postNumbers);
// print each of the sensor values
Serial.print("Temperature = ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity = ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("Pressure = ");
Serial.print(pressure);
Serial.println(" kPa");
Serial.print("Illuminance = ");
Serial.print(illuminance);
Serial.println(" lx");
Serial.print("UVA = ");
Serial.println(uva);
Serial.print("UVB = ");
Serial.println(uvb);
Serial.print("UV Index = ");
Serial.println(uvIndex);
}
unsigned long getTime()
{
// get the current time from the WiFi module
return WiFi.getTime();
}
void connectWiFi()
{
Serial.print("Attempting to connect to SSID: ");
Serial.print(ssid);
Serial.print(" ");
while (WiFi.begin(ssid, pass) != WL_CONNECTED)
{
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println();
Serial.println("You're connected to the network");
Serial.println();
}
void connectMQTT()
{
Serial.print("Attempting to MQTT broker: ");
Serial.print(broker);
Serial.println(" ");
while (!mqttClient.connect(broker, 8883))
{
// failed, retry
Serial.print(".");
Serial.println(mqttClient.connectError());
delay(5000);
}
Serial.println();
Serial.println("You're connected to the MQTT broker");
Serial.println();
// subscribe to a topic
mqttClient.subscribe("channels/899906/subscribe/fields/field8/F35GLOFJ8L99D0OM");
}
void publishMessage()
{
Serial.println("Publishing message");
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage("channels/899906/publish/DLQ0F7W5FGVO1I9Q");
String dataString = String("field1=") + String(temperature) + String("&field2=") + String(illuminance);
mqttClient.print(dataString);
mqttClient.endMessage();
/*
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage("channels/899906/publish/fields/field1/DLQ0F7W5FGVO1I9Q");
mqttClient.print(temperature);
mqttClient.endMessage();
mqttClient.beginMessage("channels/899906/publish/fields/field2/DLQ0F7W5FGVO1I9Q");
mqttClient.print(illuminance);
mqttClient.endMessage();
*/
}
void onMessageReceived(int messageSize)
{
// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available())
{
Serial.print((char)mqttClient.read());
}
Serial.println();
Serial.println();
}
This sounds like it is most likely either a typo in your URL/key or a problem on the back end. Are you receiving data whenever you make an ajax call? It might be beneficial to put a simple console.log in your .then statements.
If you URL is inaccurate, if your key is off, or if there is a bug on the API, that would explain why the value is not updating. There may also be an error with your request. It looks like you're trying to update a value in the API, but you're using a get request. While that should work, it is uncommon for users to modify back end data with a get request. Double check that the back end is not expecting a put or post request in order to update this variable.

Websocket send image file by Javascript client

I'm writing a simple application in which a javascript web socket client has to send image to a webscoket implemented by tomcat and Java language.
when I send a string message every thing is going well but #Onmessage event don't be fired if I send an image data. I've spent 2 days but haven't the solution yet.
Java WebSocket Code:
#ServerEndpoint("/sendfile")
public class BinaryWebSocketServer {
private
static final Set<Session> sessions =
Collections.synchronizedSet(new HashSet<Session>());
#OnOpen
public void onOpen(Session session) {
sessions.add(session);
System.out.println("onOpen_File::" + session.getId());
}
#OnClose
public void onClose(Session session) {
sessions.remove(session);
System.out.println("onClose_File::" + session.getId());
}
#OnMessage
public void onMessage(byte[] data, Session session) {
System.out.println("onByteArrayMessage::From=" + session.getId() + " with len:" + data.length );
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2;
try {
bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("image created");
}
#OnError
public void onError(Throwable t) {
System.out.println("onError::" + t.getMessage());
}
}
Javascript Client:
<body>
<h2>File Upload</h2> Select file
<input type="file" id="filename" />
<br>
<input type="button" value="Connect" onclick="connectChatServer()" />
<br>
<input type="button" value="Upload" onclick="sendFile()" />
<input onclick="wsCloseConnection();" value="Disconnect" type="button">
<br />
<textarea id="echoText" rows="5" cols="30"></textarea>
<script>
var webSocket = new WebSocket("ws://192.168.1.55:8081/Hello-Capture/sendfile");
webSocket.binaryType = 'arraybuffer';
webSocket.onopen = function(message){ wsOpen(message);};
//webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ wsClose(message);};
webSocket.onerror = function(message){ wsError(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Message sended to the server : " + message.value + "\n";
message.value = "";
}
function wsCloseConnection(){
webSocket.close();
}
function wsGetMessage(message){
echoText.value += "Message received from to the server : " + message.data + "\n";
}
function wsClose(message){
echoText.value += "Disconnect ... \n";
}
function wsError(message){
echoText.value += "Error ..." + message.code +" \n";
}
function sendFile() {
var file = document.getElementById('filename').files[0];
var reader = new FileReader();
var rawData = new ArrayBuffer();
reader.loadend = function(e) {
};
reader.onload = function(e) {
var rawData = e.target.result;
var byteArray = new Uint8Array(rawData);
var fileByteArray = [];
webSocket.send(byteArray.buffer);
echoText.value =("the File has been transferred.\n");
};
reader.readAsArrayBuffer(file);
}
</script>
</body>
Finally I find the solution so I comment it maybe some one else gets stuck into.
I've forgotten to pass a boolean parameter to onMessage function.
the correct form is :
#OnMessage
public void onMessage(byte[] data,boolean last, Session session) {
.
.
.
}

Subscribe to Kafka Topics over websocket from client side

We are trying to listen to the kafka topics using js code from browser once the Producer from server side pushes messages to the particular kafka topic.
In the server side, kafka server and zookeeper are running at 9092 and 2181 port respectively.
String topicName = "test";
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
props.put("partitioner.class",
"org.apache.kafka.clients.producer.internals.DefaultPartitioner");
Thread.currentThread().setContextClassLoader(null);
Producer<String, String> producer = new KafkaProducer <String, String>(props);
for(int i = 0; i < 10; i++){
producer.send(new ProducerRecord<String, String>(topicName,
Integer.toString(i), Integer.toString(i) + i));
}
producer.close();
}catch(Exception e){
e.printStackTrace();
}
Client code snippet:
<!DOCTYPE html>
<html>
<head>My Page</head>
<script src="stomp.js"></script>
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script type="text/javascript">
console.log('Starting: ');
var socket = new SockJS('ws://localhost:9092');
client = Stomp.over(socket);
client.connect( "", "",
function() {
console.log('Connected: ');
client.subscribe("/topic/test",
function( message ) {
alert( message );
}
);
}
);
</script>
</html>
From client side, while we are trying to connect via ws, only the Starting: console is getting printed and Connected: is not getting rpinted since the
websocket connection to the kafka server is not getting succeeded.
Since STOMP is not directly supported for Kafka, we tried to sue SockJS.
Can anyone please help us out to achieve this functionality.

How to Pass the hashmap value from a java file to Javascript

I am trying to retrieve the value from DataBase using Java File and storing it to HashMap. Please find the below code (Sample.java):
import java.sql.*;
import java.util.HashMap;
public class Sample {
static Connection conn;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project="Project1";
public static HashMap< String, String> map = new HashMap< String, String>();
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue","root","root");
stmt=conn.prepareStatement("select * from TestCase where ProjectName= ?");
stmt.setString(1,project);
rs=stmt.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getInt(2)+" "+rs.getInt(3)+" "+rs.getInt(4)+" "+rs.getInt(5));
map.put("ProjectName", rs.getString(1));
map.put("Total TestCase", String.valueOf(rs.getInt(2)));
map.put("TestCase Executed", String.valueOf(rs.getInt(3)));
map.put("Failed TestCase", String.valueOf(rs.getInt(4)));
map.put("TestCase Not Executed", String.valueOf(rs.getInt(5)));
System.out.println("ProjectName "+map.get("ProjectName"));
}
conn.close();
}
catch(Exception e)
{ System.out.println(e);}
}
}
Please find the below data which I am retrieving from the databse:
ProjectName TotalTestCase TestCaseExecuted TestCaseFailed TestCaseNotExecuted
Project1 50 30 8 20
I want to pass this value to Javascript and so that I am able to draw a chart using these values. Please find my HTML/Javascript code below (test.html):
<html>
<head>
</head>
<body>
<select id="ChartType" name="ChartType" onchange="drawChart()">
<option value = "PieChart">Select Chart Type
<option value="PieChart">PieChart
<option value="Histogram">Histogram
<option value="LineChart">LineChart
<option value="BarChart">BarChart
</select>
<div id="chart_div" style="border: solid 2px #000000;"></div>
<p id="demo"></p>
<p id="demo1"></p>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var row = [];
var temp;
var stri;
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(getValues);
function getValues() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
stri = xmlhttp.responseText;
drawChart();
}
};
xmlhttp.open("GET", "sample.java", true);
xmlhttp.send();
}
function drawChart() {
var data = new google.visualization.DataTable();
str = stri.split(",");
// How to call the value from java file so that I will be able to draw the below graph by passing the value.
data.addRows(row);
var a = document.getElementById("ChartType").value;
document.getElementById("demo1").innerHTML = "You selected: " + a;
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300
};
var chart = new google.visualization[document.getElementById("ChartType").value](document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</body>
</html>
Please let me know how to proceed or if anyone have any other example. Please share it with me. Thank you
You can convert your map to JSON. Instead of this
HelloWorld class, you can convert it into a service that returns this `JSON
import java.sql.*;
import java.util.HashMap;
public class Sample {
static Connection conn;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project = "Project1";
public static HashMap < String, String > map = new HashMap < String, String > ();
//Notice how your main class is now converted into a service
public static String getProjects() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue", "root", "root");
stmt = conn.prepareStatement("select * from TestCase where ProjectName= ?");
stmt.setString(1, project);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getInt(2) + " " + rs.getInt(3) + " " + rs.getInt(4) + " " +
rs.getInt(5));
map.put("ProjectName", rs.getString(1));
map.put("Total TestCase", String.valueOf(rs.getInt(2)));
map.put("TestCase Executed", String.valueOf(rs.getInt(3)));
map.put("Failed TestCase", String.valueOf(rs.getInt(4)));
map.put("TestCase Not Executed", String.valueOf(rs.getInt(5)));
System.out.println("ProjectName " + map.get("ProjectName"));
/*______________ NEW CODE ______________*/
JSONObject resultMap = new JSONObject(map);
return resultMap.toString();
}
} catch (Exception e) {
System.out.println(e);
} finally {
conn.close();
}
return "";
}
}
Now convert your test.html to test.jsp and call that service
that we've created in previous step and output the resultant JSON
into a javascript variable.
test.jsp
<%#page import="com.path.to.Sample"%>
<html>
<head>
<script>
<!-- call that service and output that json into a javascript variable -->
var resultantJSON = <%= Sample.getProjects() %>
<!-- Now all that's left is to parse that json -->
var projects = JSON.parse(resultantJSON);
</script>
</head>
<body>
...
...
</body>
</html>
Now all your results that you fetched from your database are in projects variable in Test.jsp. You can use them like conventional javascript object in your jsp file.
You have to make the Java code accessable via http. There are several ways to do this. You can implement a servlet which retrieves the http request and can send data back as httpresponse. Search for a tutorial on java servlet, e.g. like this http://www.tutorialspoint.com/servlets/servlets-first-example.htm
You could also use a java rest service to supply the information. Search for java rest tutorial, e.g. like this http://www.vogella.com/tutorials/REST/article.html

How to update data using real-time (SignalR)

I am writing to seek help, in regards creating a real-time data update using SignalR. I am currently having issue on the client-side, where I am unable to render the data content.
I have a tested the query command and it seems to be returning data. This leads me to believe, that my client-side code, maybe incorrect.
<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript" ></script>
<script src="~/Scripts/jquery.signalR-2.0.1.min.js" type="text/javascript" ></script>
<script src="~/signalr/hubs" type="text/javascript" ></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.NotificationHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.recieveNotification = function (role, descrip) {
// Add the message to the page.
$('#spanNewMessages').text(role);
$('#spanNewCircles').text(descrip);
};
// Start the connection.
$.connection.hub.start().done(function () {
notifications.server.sendNotifications(function () {
alert("does it work");
});
}).fail(function (e) {
alert(e);
});
</script>
<h1>New Notifications</h1>
<div>
<b>New <span id="spanNewMessages"></span> role.</b><br />
<b>New<span id="spanNewCircles"></span> descrip.</b><br />
</div>
Hub Class:
[HubName("NotificationHub")]
public class notificationHub : Hub
{
string role = "";
string descrip = "";
[HubMethodName("sendNotifications")]
public void SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ConnectionString))
{
string query = "SELECT [role],[description] FROM [dbo].[User]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
role = dt.Rows[0]["role"].ToString();
descrip = dt.Rows[0]["description"].ToString();
}
}
}
Clients.All.RecieveNotification(role, descrip);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
notificationHub nHub = new notificationHub();
nHub.SendNotifications();
}
}
}
StartUp CLass:
using Microsoft.Owin;
using Owin;
using WebApplication2;
namespace WebApplication2
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Could anyone, please provide some assistant, to where I may be going wrong with this task. Thank you.
I mocked up your app. Your issue was you are returning a string from your hub action:
public string SendNotifications()
{
return context.Clients.All.RecieveNotification(role, descrip);
}
this should be void (you aren't returning anything, but actually calling the clients), and you also don't need to use GlobalHost to get the context here, only when the context isn't available (I.E. calling the hub from the server). Try making these changes:
[HubMethodName("sendNotifications")]
public void SendNotifications()
{
//using...
//IHubContext context = GlobalHost.ConnectionManager.GetHubContext<notificationHub>();
//return context.Clients.All.RecieveNotification(role, descrip);
Clients.All.RecieveNotification(role, descrip);
}
Put a breakpoint at Clients.All... and see if it is being triggered. Let me know if these updates fix your issue.

Categories