I've created a iisnode WebSocket server using ws module. The problem I'm encountering is although the client is sending String data to the server the server is receiving the data as a Binary Message.
Client Side JS
var socket;
window.addEventListener('load', function(){
socket = new WebSocket('wss://server/ws/');
socket.addEventListener('open', function (event) {
console.log('Hello Server!');
socket.send('Hello Server!');
});
socket.addEventListener('message', function (event) {
console.log('Message from server : ', event.data);
});
socket.onerror = function(event){
console.log('Error : ', event);
};
socket.onclose = function(event){
console.log('Close : ', event);
};
});
Server Side JS
var express = require("express");
var app = express();
var WebSocket = require("ws");
var server = app.listen(process.env.PORT, function(){
console.log("listening");
});
var wss = new WebSocket.Server({"server":server});
wss.on("connection", function(user){
user.send("connected");
user.on("message", function(message){
wss.clients.forEach(function(client){
if(client.readyState===WebSocket.OPEN){
client.send(typeof(message));
client.send(message);
};
});
});
});
app.get("/ws/", function(req, res) {
res.send("WebSocket");
});
web.cofig
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="node_app.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules>
<rule name="ws" patternSyntax="ECMAScript" stopProcessing="true">
<match url="^ws/?$" />
<action type="Rewrite" url="\ws\node_app.js" />
</rule>
</rules>
</rewrite>
<webSocket enabled="false" />
</system.webServer>
</configuration>
When I run the code the data I'm getting back is :
| ↑↓ | Data | Value |
| -------- | -------------- | ---------------------------------------------------------------- |
| ↑ | Hello Server! | Hello Server! |
| ↓ | connected | connected |
| ↓ | object | object |
| ↓ | Binary Message | 00000000: 4865 6c6c 6f20 5365 7276 6572 21 Hello Server! |
From everything I have seen online the data that I'm receiving on the server side should be a as String "Hello Server!" so I'm unsure why the data sever side is an object?
So again in everything I've read no one mentioned this but message.toString()
seems to have done the trick.
Server Side JS
var express = require("express");
var app = express();
var WebSocket = require("ws");
var server = app.listen(process.env.PORT, function(){
console.log("listening");
});
var wss = new WebSocket.Server({"server":server});
wss.on("connection", function(user){
user.send("connected");
user.on("message", function(message){
var message = message.toString();
wss.clients.forEach(function(client){
if(client.readyState===WebSocket.OPEN){
client.send(typeof(message));
client.send(message);
};
});
message = null;
});
});
app.get("/ws/", function(req, res) {
res.send("WebSocket");
});