I am trying to impliment websocket chat in mvc5 application using node.js and websocket for this I am using URL rewriter.
I am created a node server with following code.
var app = require('express')();
//creating http server
var server = require('http').createServer(app);
//add webrtc.io functionality to http server
var webRTC = require('webrtc.io').listen(server);
//port which is allocated dynamically by visual studeo IIS/iisexpress server, which of string formate.
var port = process.env.PORT;
//let the server in listen mode for the port id assigned by IIS server.
server.listen(port);
//this is for testing purpose, which returns the string, for the specified url request
app.get('/test/websocketcon', function (req, res)
{
res.end("working");
});
If i am trying to to access the https://localhost:44300/test/websocketcon. I am getting response as "working". But If I am trying to create new websocket I am getting error as
WebSocket connection to 'wss://localhost:44300/Home/websocketcon' failed: Error during WebSocket handshake: Unexpected response code: 404
Code I have tried to create new websocket
var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = protocol + window.location.host + window.location.pathname + "/websocketcon";
var createdwebsocket = new WebSocket(address );
your express route/server listens on for http requests, not wss. check this out: https://www.npmjs.com/package/express-ws
To explain in depth:
With the following lines of code, you have created a http server:
var app = require('express')();
var server = require('http').createServer(app);
http is what protocol you use when when you connect to http://yoursite.com
. However, you are trying to connect a websocket to your server. to do this, you need to add a websocket listener and route to your server. This is because websockets don't work over the http protocol, they work over the websocket protocol.
To make a websocket server, checkout the link/module I have provided above. You should have a server which listens for both http requests and websocket requests. To make your current code work with websockets, what you need to do is make the following changes:
var app = require('express')();
var server = require('http').createServer(app);
// now add the express websocket functionality
var expressWs = require('express-ws')(app);
.
.
.
app.ws('/test/websocketcon', function (ws, req)
{
ws.send("Working!");
ws.on('message', function(msg) {
ws.send(msg);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With