WCF Full Duplex Application with Websocket Client - javascript

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

Related

WebSocket not showing js alert

I have been advised that the solution in another SO post of mine might involve WebSocket. It just closes the connection instantly when used with my Url, but the javascript.info Url works fine. But why is that?
console.log says:
WebSocket connection to 'wss://verlager.com/hello' failed:
function sentry() {
if ("WebSocket" in window) {
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
// THIS WORKS:
let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");
// But my server doesn't work! Why doesn't it work on my server?
var ws = new WebSocket("wss://verlager.com/hello");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
console.log("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
console.log("Message is received...");
};
ws.onclose = function() {
// websocket is closed.
console.log("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
console.log("WebSocket NOT supported by your Browser!");
}
}
sentry();
First, I've encountered an error with the exact same format, when I tried to connect to wss://localhost, which wasn't running.
Try specifying the port of your server, I'm not sure which one it assumes by default. Also make sure that your server is running secure websockets and it's dealing correctly with your path /hello.

How can i use socket communication between java server and javascript client?

I'm trying to connect java Server and Javascript client with socket.io. When i see the debugger at browser, it looks like the data is being received, but i'm getting this error: "Reason: CORS header 'Access-Control-Allow-Origin' missing" and i am not being able to print data at client-side.
import...
public class MeuServerSocket {
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public MeuServerSocket(int port) {
// starts server and waits for a connection
try {
while(true){
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
ObjectOutputStream saida = new ObjectOutputStream(socket.getOutputStream());
saida.flush();
// send available data from server to client
saida.writeObject("Texto enviado 123...");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
boolean fim = false;
while (!line.equals("Over") && !fim)
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
fim = true;
System.out.println(i.toString());
}
}
System.out.println("Closing connection");
// close connection
socket.close();
saida.close();
in.close();
}
} catch (IOException i) {
System.out.println(i);
}catch(Exception e){
System.out.println(e.toString());
}
}
public static void main(String[] args) {
MeuServerSocket server = new MeuServerSocket(5000);
}
}
var socket = io('http://localhost:5000');
socket.on('connect', function () {
socket.send('hi \nOver');
socket.on('get', function (msg) {
// my msg
console.log('msg: '+msg)
})
socket.on('disconnect',()=>{
console.log('disconnected')
})
})
When i look at Firefox network, i see that the data was sent inside one of the packages...
https://imgur.com/vDAS00B
The biggest issue I'm seeing here is a misunderstanding of socket.io. Socket.io for javascript is not compatible with the Socket library in java. The naming conventions can be confusing for sure.
socket.io is a library that is related to web sockets (ws://). It implements all the basic websocket features plus some bonuses.
What you have for your java code is a TCP socket server. While websockets and socket.io are built on TCP socket, you can not connect a socket.io client to a "naked" socket server.
SOLUTION:
If your javascript is running from nodejs, you can use their net library found here. If you are running javascript from a webbrowser, than you are limited to websockets, which means you're going to change your java code to a websocket server. You can find a library for that somewhere online.
TLDR: Use ws://... instead of http://....
Details:
https is used for HTTP protocol. In such case it is correct that browser first asks your server if CORS is allowed. You have not enabled CORS. That's why it is normal that browser refuses to send CORS request.
But you say you want to use Web Sockets. Then you should use ws://, not http://. For Web Sockets there is no CORS policy and browser will send your request without CORS restrictions.

HTML 5 Web Sockets channels routing

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?

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!

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