I have following code as a server:
var http = require('http'),
cors = require('cors'),
connect = require('connect'),
WebSocketServer = require('ws');
var DataController = function() {
this.PORT = 8090;
this.startWS();
this.startServer();
}
DataController.prototype = {
// code to start server...
getMessage: function(_message) {
var that = this,
message = JSON.parse(_message),
msgName = message.name;
console.log('new message ' + msgName);
switch(msgName){
case 'start':
// here is some code to perform actions
}
As you can see here I have getMessage function that fires some events and to invoke it I need to send a message start. That's easy enough, right? Surpisingly for me, it's not.
That's how I try to perform this .send() method in my React component (my React app is running on different port of course):
import React, { Component } from 'react';
class App extends Component {
componentDidMount() {
const socket = new WebSocket('ws://localhost:8090');
socket.onopen = function() {
socket.send(JSON.stringify({message: "start"}));
}
}
render() {
return (
<div className="container">App</div>
)
}
}
export default App;
What I try to accomplish here - I need to send just one word - start to actually start receieving data from server but I can't and do not understand why. See, there's a console.log() statement in my server code that logs a message start when it's sent. So it actually should log start but it logs undefined instead.
What I tried so far:
1. Send just start
2. Define an object like this:
const data = {
message: "start"
}
And then pass data to .send() function
3. Define just a variable like this: const data = "start"
And nothing above works!Everything returns undefined on server side. I'm just getting started with websockets and can't find a way to get it working. I refered mostly to Mozilla and it didn't work too. So what actually am I doing wrong in this case? Thanks in advance, I appreciate any help!
socket.onopenhandler to the correct context?8090and8091.