Cannot connect to ASP.NET Core websocket from javascript - javascript

I created a simple ASP.NET websocket server from the sample app at https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/websockets/samples/2.x/WebSocketsSample
Works great from the provided Razor page...
Here is part of the server code that accepts the socket connection.
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(context, webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
But now using code adapted from https://www.websocket.org/echo.html it fails badly...
Here is the part of the adapted code...
// var wsUri = "wss://echo.websocket.org/";
var wsUri = "ws://localhost:36472/ws"
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
Is this the expected behavior?! Is there no way for javascript and ASP.NET Core to interoperate through websockets?!

I tried to replicate your issue, but it seems to be working fine.
I started a new .NET Core project and I added a code from WebSocketsSample you've mentioned:
Startup.cs
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebApplication3
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var webSocketOptions = new WebSocketOptions()
{
KeepAliveInterval = TimeSpan.FromSeconds(120),
ReceiveBufferSize = 4 * 1024
};
app.UseWebSockets(webSocketOptions);
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(context, webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseMvc();
}
private async Task Echo(HttpContext context, WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
}
Program.cs
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace WebApplication3
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
On the UI side I created an empty page and pasted a JS code your provided:
Index.cshtml
#page
#model IndexModel
#{
ViewData["Title"] = "";
}
<div id="output"></div>
#section Scripts{
<script language="javascript" type="text/javascript">
//var wsUri = "wss://echo.websocket.org/";
var wsUri = "wss://localhost:44357/ws";
var output;
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function (evt) { onClose(evt) };
websocket.onmessage = function (evt) { onMessage(evt) };
websocket.onerror = function (evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');
websocket.close();
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
}
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebApplication</title>
</head>
<body>
<div>
#RenderBody()
</div>
#RenderSection("Scripts", required: false)
</body>
</html>
And here is a result I'm getting:
Just in case here is a zip archive with code: https://ufile.io/pm2ljcbn
So your code should be fine. Am I missing anything?

Related

NodeJS unable to modify a class obj

this is my first post in this forum. So please forgive me the misstakes.
I want to write a NodeJS server which runs a WebSocket Server (npm ws module).
The NodeJS server contains also a Class Obj which i want to modify a funciton afterwards over the Websocket server.
My Problem is the modified functjion cant acces global variables.
Can someone help if there is a solution for this problem or why this happes because if you do this without the Websocket it works.
Here is the code:
Server code:
const WebSocket = require('ws');
// WebSocket Server
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
try {
message = JSON.parse(message);
if (message.type == "handler") {
handler.modify(message.data);
console.log("modifyed");
}
if (message.type == "func") {
handler.modify_func(message.data);
console.log("modifyed");
}
if (message.type == "run") {
eval(message.data);
}
}
catch (error) {
}
});
});
// Modifying class
class Handler {
constructor() {
this.functions = [];
}
modify(data) {
let temp_class = new Function('return ' + data)();
temp_class.functions.forEach(element => {
if (this.functions.indexOf(element) == -1) {
this.functions.push(element)
}
this[element] = temp_class[element];
});
}
modify_func(data) {
let temp_func = new Function('return ' + data)();
this[temp_func.name] = temp_func;
}
test_func_from_orginal() {
console.log("test_func_from_orginal says:");
console.log(test_val);
}
}
var test_val = "this is the global variable";
var handler = new Handler();
Client code:
const WebSocket = require('ws');
//WebSocket Client
var ws = new WebSocket('ws://localhost:8080');
ws.on('open', function open(event) {
// ws.send(JSON.stringify({ type: "handler", data: Handler.toString() }))
ws.send(JSON.stringify({ type: "func", data: test_func_from_func.toString() }))
console.log("open")
});
//Class Module
class Handler {
static get functions() {
return ["test"];
}
static test_func_from_class() {
console.log("test_func_from_class sayes:")
console.log(test_val);
}
}
function test_func_from_func() {
console.log("test_func_from_func sayes:")
console.log(test_val);
}
setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.test_func_from_orginal()' })) }, 1000);
// setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.test_func_from_class()' })) }, 1000);
setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.test_func_from_func()' })) }, 1000);
Ok, so this is what it's all about - a simple mistake. If you cut out all the websocket stuff (which is not really relevant here, as strings, and not contexts, got passed from and back anyway), you'll get this:
class ServerHandler {
constructor() {
this.functions = [];
}
modify(data) {
let temp_class = new Function('return ' + data)();
// not sure why not just `eval(data)` btw
temp_class.functions.forEach(funcName => {
if (this.functions.indexOf(funcName) == -1) {
this.functions.push(funcName)
}
this[funcName] = temp_class[funcName];
});
}
}
class ClientHandler {
static get functions() {
return ["test_func_from_class"];
// not "test" as in your example
// you actually don't even need this registry:
// all the static methods can be collected in runtime
}
static test_func_from_class() {
console.log("test_func_from_class sayes:")
console.log(test_val);
}
}
var test_val = 42;
var handler = new ServerHandler();
handler.modify(ClientHandler.toString());
eval(`handler.test_func_from_class()`); // 42
This all works fine, as there's no longer a mismatch between a name of method stored in static get functions ("test") and actual name of that method ("test_func_from_class"). The trick is that all the static functions created along with that temporary class are scoped the same way any other entity created in ServerHandler; that's how they 'see' that test_val.
But 'works' here is about mere possibility of this approach from technical perspective, and not about feasibility. Both new Function and eval with arbitrary input are very dangerous security holes - and they're left wide open here.
I found now a solution for my problem.
Server Code
const WebSocket = require('ws');
// WebSocket Server
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
message = JSON.parse(message);
try {
if (message.type == "run") {
eval(message.data);
}
if (message.type == "obj_handler") {
handler.modify(JSON.parse(message.data));
}
}
catch (error) {
console.log(error);
}
// console.log('received: %s', message);
});
ws.send('something');
});
class ServerHandler {
constructor() {
this.data = "hi";
}
modify(data) {
for (const func in data) {
this[func] = eval(data[func]);
}
}
}
var test_val = 42;
var handler = new ServerHandler();
Client Code:
const WebSocket = require('ws');
//WebSocket Client
try {
var ws = new WebSocket('ws://localhost:8080');
ws.on('open', function open(event) {
ws.send(JSON.stringify({ type: "obj_handler", data: update.convert() }))
});
}
catch (error) {
}
// Needed Update with 2 new Functions
update = {
func_test_global: () => {
console.log(test_val);
},
func_test_this: _ => {
console.log(this.data);
},
convert: function () {
let new_update = {};
for (const func in this) {
if (func != "convert")
new_update[func] = "" + this[func];
}
return JSON.stringify(new_update)
}
}
// setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.func_test_global()' })) }, 1000);
// setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.func_test_this()' })) }, 1000);

How can I call the methods in another pure class in react-native?

I got a class to help websocket communication as a single file, here's the code(note this class not extends component):
import {
DeviceEventEmitter,
} from 'react-native';
import { observer, inject } from 'mobx-react';
let that = null;
class WebSocketClient {
constructor() {
this.ws = null;
that = this;
this.prefixUrl = this.props.globalVarStore.serverAddr + 'ws/chat/' + this.genId() + '/';
}
/**
* get WebSocket instance
* #returns {WebSocketClient}
*/
static getInstance() {
if (!this.instance) {
this.instance = new WebSocketClient();
}
return this.instance;
}
/**
* generate uuid
*/
static genId() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).toUpperCase();
}
/**
* initialize WebSocket
*/
initWebSocket() {
try {
this.timer && clearInterval(this.timer);
this.ws = new WebSocket(this.prefixUrl);
this.initWsEvent();
} catch (e) {
console.log('WebSocket err:', e);
this.reconnect();
}
}
/**
* initialize WebSocket events
*/
initWsEvent() {
this.ws.onopen = function () {
console.log('WebSocket:', 'connect to server');
};
this.ws.onmessage = function (evt) {
if (evt.data !== 'pong') {
console.log('WebSocket: response msg', evt.data);
DeviceEventEmitter.emit('pushEmitter', '');
} else {
console.log('WebSocket: response pong msg=', evt.data);
}
};
this.ws.onerror = function (err) {
console.log('WebSocket:', 'connect to server error');
that.reconnect();
};
this.ws.onclose = function () {
console.log('WebSocket:', 'connect close');
that.reconnect();
};
this.timer = setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
console.log('WebSocket:', 'ping');
this.ws.sendMessage('ping');
}
}, 15000);
}
sendMessage(msg) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
try {
this.ws.send(msg);
} catch (err) {
console.warn('ws sendMessage', err.message);
}
} else {
console.log('WebSocket:', 'connect not open to send message');
}
}
reconnect() {
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = setTimeout(function () {
this.initWebSocket();
}, 15000);
}
}
export default WebSocketClient;
Then i import it in APP.js to make a connect. I put it in the componentDidMount() function as follow:
componentDidMount() {
const ws = new webSocketClient();
ws.initWebSocket();
ws.initWsEvent();
//Here I want to save the instance in the mobx so i can easily get it and send message
this.props.messageStore.saveWs(ws);
}
But when I run on my Android device, it show ws.initWebSocket is not a function.
wrong info
So how to use a pure class in react native? Or there is not a pure class in React?
Thanks!
Would be happening 2 things.
A) You have not imported the class.
B) When you create a new WebSocketClient you use it with the first letter in lowercase. Should be:
const ws = new WebSocketClient();
instead of what you have that is
const ws = new webSocketClient();
note the change: w => W

WebRTC Peer to Peer only display local stream twice

I'm trying to learn how to use this new cool WebRTC API.
I'm following this tutorial, https://simpl.info/rtcpeerconnection/ but I don't understand how to get the second stream from my Raspberry Pi 3 running UV4L server https://www.linux-projects.org/webrtc-signalling/
I have tested it the functionality with UV4L built-in WebRTC page using websockets and it works.
Here is my code so far, but it only displays my local stream twice in the local and remote video tags.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1" name="viewport">
<title>Peer connection</title>
</head>
<body>
<div id="container">
<video autoplay="" id="localVideo"></video> <video autoplay="" id="remoteVideo"></video>
<div>
<button id="startButton">Start</button> <button id="callButton">Call</button>
<button id="hangupButton">Hang Up</button>
</div>
</div>
<script src="js/main.js">
</script>
</body>
</html>
JavaScript:
var startButton = document.getElementById('startButton');
var callButton = document.getElementById('callButton');
var hangupButton = document.getElementById('hangupButton');
callButton.disabled = true;
hangupButton.disabled = true;
startButton.onclick = start;
callButton.onclick = call;
hangupButton.onclick = hangup;
var startTime;
var localVideo = document.getElementById('localVideo');
var remoteVideo = document.getElementById('remoteVideo');
var localStream;
var pc1;
var pc2;
var offerOptions = {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1,
};
function getName(pc) {
return pc === pc1 ? 'pc1' : 'pc2';
}
function getOtherPc(pc) {
return pc === pc1 ? pc2 : pc1;
}
function gotStream(stream) {
localVideo.srcObject = stream;
localStream = stream;
callButton.disabled = false;
}
function start() {
startButton.disabled = true;
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true,
})
.then(gotStream)
.catch(function(e) {
alert('getUserMedia() error: ' + e.name);
});
}
function call() {
callButton.disabled = true;
hangupButton.disabled = false;
startTime = window.performance.now();
var videoTracks = localStream.getVideoTracks();
var audioTracks = localStream.getAudioTracks();
// MY UV4L stun server
var servers = {
iceServers: [ { urls: [ 'stun:' + '192.84.178.59' + ':3478' ] } ],
};
pc1 = new RTCPeerConnection(servers);
pc1.onicecandidate = function(e) {
onIceCandidate(pc1, e);
};
console.log(servers);
pc2 = new RTCPeerConnection(servers);
pc2.onicecandidate = function(e) {
onIceCandidate(pc2, e);
};
pc1.oniceconnectionstatechange = function(e) {
onIceStateChange(pc1, e);
};
pc2.oniceconnectionstatechange = function(e) {
onIceStateChange(pc2, e);
};
pc2.ontrack = gotRemoteStream;
localStream.getTracks().forEach(function(track) {
pc1.addTrack(track, localStream);
});
pc1.createOffer(offerOptions).then(onCreateOfferSuccess, onCreateSessionDescriptionError);
}
function onCreateSessionDescriptionError(error) {
console.log(error.toString());
}
function onCreateOfferSuccess(desc) {
pc1.setLocalDescription(desc).then(function() {
onSetLocalSuccess(pc1);
}, onSetSessionDescriptionError);
pc2.setRemoteDescription(desc).then(function() {
onSetRemoteSuccess(pc2);
}, onSetSessionDescriptionError);
pc2.createAnswer().then(onCreateAnswerSuccess, onCreateSessionDescriptionError);
}
function onSetLocalSuccess(pc) {
console.log(getName(pc) + ' setLocalDescription complete');
}
function onSetRemoteSuccess(pc) {
console.log(getName(pc) + ' setRemoteDescription complete');
}
function onSetSessionDescriptionError(error) {
console.log('Failed to set session description: ' + error.toString());
}
function gotRemoteStream(e) {
if (remoteVideo.srcObject !== e.streams[0]) {
console.log(e.streams[0]);
remoteVideo.srcObject = e.streams[0];
}
}
function onCreateAnswerSuccess(desc) {
pc2.setLocalDescription(desc).then(function() {
onSetLocalSuccess(pc2);
}, onSetSessionDescriptionError);
pc1.setRemoteDescription(desc).then(function() {
onSetRemoteSuccess(pc1);
}, onSetSessionDescriptionError);
}
function onIceCandidate(pc, event) {
getOtherPc(pc).addIceCandidate(event.candidate).then(
function() {
onAddIceCandidateSuccess(pc);
},
function(err) {
onAddIceCandidateError(pc, err);
},
);
}
function onAddIceCandidateSuccess(pc) {
console.log(getName(pc) + ' addIceCandidate success');
}
function onAddIceCandidateError(pc, error) {
console.log(getName(pc) + ' failed to add ICE Candidate: ' + error.toString());
}
function onIceStateChange(pc, event) {
if (pc) {
console.log(getName(pc) + ' ICE state: ' + pc.iceConnectionState);
console.log('ICE state change event: ', event);
}
}
function hangup() {
pc1.close();
pc2.close();
pc1 = null;
pc2 = null;
hangupButton.disabled = true;
callButton.disabled = false;
}

Android Receiving Messages From WebSocket Server

I am working on an Android application where I need to connect to a web socket and receive messages to unlock the app from the web server. Receiving messages have been implemented through Stompclient on java script but i need to do the same on Android. I read about Okhttp3 and its support for web socket so I was able to implement it The websocket is opening but I don't know how to subscribe to receive the messages on Android.
Here is the Java Script Code:
<html>
<head>
<title>Chat WebSocket</title>
<script src="/gravity/resources/sockjs-0.3.4.js"></script>
<script src="/gravity/resources/stomp.js"></script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility
= connected ? 'visible' : 'hidden';
document.getElementById('response').innerHTML = '';
}
function connect() {
var socket = new SockJS('/gravity/api/gravitywebsocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/pos/asycnronous', function(messageOutput) {
var body = messageOutput.body; body.a=5;
showMessageOutput(body);
});
});
}
function disconnect() {
if(stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendMessage() {
var from = document.getElementById('from').value;
var text = document.getElementById('text').value;
stompClient.send("/api/poschannel", {},JSON.stringify({'from':from, 'text':text}));
}
function showMessageOutput(messageOutput) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(messageOutput.a + "***" +messageOutput.from + ": "
+ messageOutput.text + " (" + messageOutput.time + ")"));
response.appendChild(p);
}
</script>
</head>
<body onload="disconnect()">
<div>
<div>
<input type="text" id="from" placeholder="Choose a nickname"/>
</div>
<br />
<div>
<button id="connect" onclick="connect();">Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">
Disconnect
</button>
</div>
<br />
<div id="conversationDiv">
<input type="text" id="text" placeholder="Write a message..."/>
<button id="sendMessage" onclick="sendMessage();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
</html>
My Android Implementation:
public class ServerConnection {
public enum ConnectionStatus {
DISCONNECTED,
CONNECTED
}
public interface ServerListener {
void onNewMessage(String message);
void onStatusChange(ConnectionStatus status);
}
private WebSocket mWebSocket;
private OkHttpClient mClient;
private String mServerUrl;
private Handler mMessageHandler;
private Handler mStatusHandler;
private ServerListener mListener;
public class SocketListener extends WebSocketListener {
#Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
try {
System.out.println("On Open: Observe Response: " + response.body().string());
} catch (Exception e) {
Utility.stringify(e);
}
Message message = mMessageHandler.obtainMessage(Contract.ACTIVATE_POS_MESSAGE, ConnectionStatus.CONNECTED);
mStatusHandler.sendMessage(message);
}
#Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
System.out.println("OnMessage: Observe result: " + text);
Message message = mMessageHandler.obtainMessage(Contract.ACTIVATE_POS_MESSAGE, text);
mMessageHandler.sendMessage(message);
}
#Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes.toString());
System.out.println("OnMessage: Observe result: " + bytes.toString());
Message message = mMessageHandler.obtainMessage(Contract.ACTIVATE_POS_MESSAGE, bytes.toString());
mMessageHandler.sendMessage(message);
}
#Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
System.out.println("OnClosed: Observe Reason: " + reason);
Message message = mMessageHandler.obtainMessage(Contract.ACTIVATE_POS_MESSAGE, ConnectionStatus.DISCONNECTED);
mMessageHandler.sendMessage(message);
}
#Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
super.onFailure(webSocket, t, response);
System.out.println("OnFailure: Observe Response: " + response);
disconnect();
}
}
public ServerConnection(String url) {
mClient = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
mServerUrl = url;
}
public void connect(ServerListener listener) {
Request request = new Request.Builder()
.url(mServerUrl)
.build();
mWebSocket = mClient.newWebSocket(request, new SocketListener());
mWebSocket.send("Hello, Testing Connection!");
mListener = listener;
mMessageHandler = new Handler(msg -> {
mListener.onNewMessage((String) msg.obj);
return true;
});
mStatusHandler = new Handler(msg -> {
mListener.onStatusChange((ConnectionStatus) msg.obj);
return true;
});
}
public void disconnect() {
mWebSocket.close(1000, "Completed");
mListener = null;
mMessageHandler.removeCallbacksAndMessages(null);
mStatusHandler.removeCallbacksAndMessages(null);
}
public void sendMessage(String message) {
mWebSocket.send(message);
}
}
The LockScreenActivity that needs to receive unlock message from server:
public class LockScreenActivity extends AppCompatActivity implements ServerConnection.ServerListener{
private ServerConnection mServerConnection;
private JSONObject jsonObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lock_screen);
mServerConnection = new ServerConnection(TerminalDetails.WEB_SOCKET_URL);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Timer timer = new Timer();
timer.schedule(timerTask, 10000);
}
#Override
protected void onResume() {
super.onResume();
mServerConnection.connect(this);
mServerConnection.sendMessage("Hello, Testing Connection!");
Utility.showToast(this, "Connected to the Web Socket");
}
#Override
public void onNewMessage(String message) {
try {
Utility.showToast(this, "A new message received!");
jsonObject = new JSONObject(message);
} catch (JSONException e) {
Utility.stringify(e);
}
validateResponse(jsonObject);
}
I will answer more questions about the code if needed. Thanks

SignalR on new relic it's on top of error rate with this request: [host]/signalr/connect/

I have a Sitefinity app hosted in Azure CloudService and I use signalr to push data to clients. Recently monitoring the app with new relic I found that the signalr its on top of error rate with this request: [host]/signalr/connect/ as you may see in the image. Also say that push work perfectly.
capture of error rate in newrelic
My Server side:
[assembly: OwinStartup(typeof(Startup))]
namespace SitefinityWebApp.FXS.Custom.AppStart
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
GlobalHost.HubPipeline.AddModule(new SignalRErrorHandler());
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true
};
app.MapSignalR(hubConfiguration);
}
}
}
namespace SitefinityWebApp.Hubs.Posts
{
public class PostHub : Hub
{
}
public class PostNotification : IPostNotification
{
private readonly static Lazy<PostNotification> instance = new Lazy<PostNotification>(() => new PostNotification());
private readonly IHubContext iHubContext;
private PostNotification()
: this(GlobalHost.ConnectionManager.GetHubContext<PostHub>())
{
}
internal PostNotification(IHubContext iHubContext)
{
this.iHubContext = Guard.ArgumentNotNullAndReturn(iHubContext, "iHubContext");
}
public static PostNotification Instance
{
get
{
return instance.Value;
}
}
public void PostCreated(string action, PostResponse post)
{
var proxy = this.iHubContext.Clients.All;
proxy.Invoke(action, post);
}
}
}
My client side:
(function () {
Class.PostNotifications = function () {
var parent = Class.Base(),
_this = Util.extendObject(parent);
_this.ReconnectionTime = 5000;
_this.PostCreated_ObserverSubject = null;
_this.PostHub = null;
_this.ContentType = "";
_this.constructor = function (contentType) {
_this.ContentType = contentType;
_this.startConnection();
_this.setVars();
_this.configurePostHub();
};
_this.setVars = function () {
_this.PostHub = $.connection.postHub;
_this.PostCreated_ObserverSubject = new Class.Patterns.Observer.Subject();
};
_this.configurePostHub = function () {
_this.PostHub.client[_this.ContentType + 'Created'] = function (post) {
_this.PostCreated_ObserverSubject.notify(post);
};
};
_this.whenPostCreated = function (functionDelegate) {
if (functionDelegate !== undefined && functionDelegate !== null) {
var json = {
'UpdateDelegate': functionDelegate
};
var observer = new Class.Patterns.Observer.Observer();
observer.init(json);
_this.PostCreated_ObserverSubject.addObserver(observer);
}
};
_this.startConnection = function () {
$.connection.hub.logging = true;
$.connection.hub.start().done(function () {
console.log("connection stablish");
}).fail(function (err) {
console.log(err);
});
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, _this.ReconnectionTime);
});
};
return _this;
};
}());
Any help would be appreciated

Categories

Resources