Here is my webserver:
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('hello\n');
socket.write('world\n');
//RECEIVE PACKET ON SOCKET
socket.on('data', function(data) {
//socket.write(data);
//console.log(data);
testSocketData(data)
});
});
server.listen(8000);
And the method testSocketData(data) is located in file update_ui.js and does the following:
function testSocketData(test) {
$('#p1').text(test)
}
Where #p1 refers to the id of a paragraph element in my main.html. I know that my socket is working, however I get:
ReferenceError: testSocketData is not defined.
How can I simply pass off the data received from my node.js server to the rest of my web application?
You must move that method(with socket.on('data') as well) from the server to the client side. When you receive a message via socket, the p1 element will update its text too.
On the server you will still need to have a socket.on('data') to receive the messages from the client.
Edit:
Here is some code, a little bit changed from my comment below.
On server:
function computeSomeResults(data) {
// your logic here
}
socket.on('servermsg', function(data) {
var result = computeSomeResults(data);
socket.emit('clientmsg', result);
});
On client:
function testSocketData(test) {
$('#p1').text(test);
}
socket.on('clientmsg', function(data) {
testSocketData(data);
// emit something maybe?
}
Eventually, you may want to send something to the server:
$('#p1').on('click', function(){
socket.emit('servermsg', $(this).text());
});
Related
I'm trying to recreate the functionality of a hardware serial server with Node and it's actually working, but I'm getting errors from socket instances that have been closed.
Here's a simplified version of the app to show what I'm doing...
var net = require('net');
var SerialPort = require('serialport');
var connectionCounter = 0;
var port = new SerialPort('/dev/ttyUSB0', function () {
var server = net.createServer();
server.on('connection',function(socket) {
connectionCounter++;
var connNumber = connectionCounter;
socket.on('error', function () {
console.log('socket ' + connNumber + ' errored');
});
socket.on('data', function(data) {
port.write(data);
});
port.on('data', function(data) {
socket.write(data);
});
});
server.listen(8887, '127.0.0.1');
}
});
So the first chunk of code that's sent into the 8887 port works fine, and it returns the data back out through the socket. The errors start on the second chunk. In the example, I'm keeping a count of the socket instances and outputting the socket instance number with the error. So as the program runs, the number of sockets instances keeps going up. The most recent instance will eventually handle the data, but I can't figure out what I need to delete to clean up all of the previous socket instances so they'll stop trying to process the incoming data.
I've tried socket.end() and socket.destroy(), but those don't seem to work . Do I need to go as far as deleting the server itself and recreating it?
If anyone ever finds this and cares about what was going wrong, I was setting an event listener on the serialport object every time a new net socket was created. So even though I was deleting the socket every time it was closed, the serialport listener was trying to send data to all of the old deleted sockets. So the solution was to removeListeners from the serialport object upon closing the net socket.
you can use array for storing sockets later on you can delete. this is sample code hope you got the idea
var net = require('net');
var SerialPort = require('serialport');
var connectionCounter = 0;
var mySockets = [];
var port = new SerialPort('/dev/ttyUSB0', function () {
var server = net.createServer();
server.on('connection',function(socket) {
mySockets.push(socket);
connectionCounter++;
var connNumber = connectionCounter;
socket.on('error', function () {
console.log('socket ' + connNumber + ' errored');
});
socket.on('data', function(data) {
port.write(data);
});
port.on('data', function(data) {
socket.write(data);
});
});
server.listen(8887, '127.0.0.1');
}
//get the sockets you want to delete
var s = mySockets.pop();
s = null;
});
I am using yii2-node-socket to send event to clients in a concrete room. I followed all steps to install the extension in my project, the server was started successfully and the client was connected to socket but when I tried to send event from php code the client did not receive any data.
Javascript code:
var socket = new YiiNodeSocket();
socket.onConnect(function () {
socket.room('testRoom').join(function (success, numberOfRoomSubscribers) {
// success - boolean, numberOfRoomSubscribers - number of room members
// if error occurred then success = false, and numberOfRoomSubscribers - contains error message
if (success) {
console.log(numberOfRoomSubscribers + ' clients in room: testRoom');
// do something
// bind events
this.on('join', function (newMembersCount) {
// fire on client join
});
this.on('data', function (data) {
// fire when server send frame into this room with 'data' event
console.log('in data : ', data);
});
} else {
// numberOfRoomSubscribers - error message
alert(numberOfRoomSubscribers);
}
});
});
PHP code:
// create frame
$frame = Yii::$app->nodeSocket->getFrameFactory()->createEventFrame();
// set event name
$frame->setEventName('data');
// set room name
$frame->setRoom('testRoom');
// set data
$frame['key'] = 'hello';
// send
$frame->send();
I'm having the most odd problem trying to send data from a client browser to my node server using SocketIO. Sending from server to client works just fine, but the other way around I get an undefined error. Here's a quick bit of what it looks like, super simple.
Node Server (app.js)
io.on("connection", function(socket) {
socket.on("pageReady", function(data) {
console.log('pageReady called');
console.log(data);
return socket.emit('newline', '###SOCKET STARTED###');
});
socket.on("disconnect", function() {
return console.log('disconnected');
});
});
Browser (client.js)
var socket;
socket = io.connect("http://localhost:5678");
socket.on("newline", function(data) {
return $('#socketData').append('<li>' + data + '</li>');
});
socket.emit("pageReady", "test");
Super simple, right? Nothing special. When I emit from server, works fine, however when the client calls "pageReady". node responds with this.
/Volumes/HOME/Users/user/git/sockettest/app.js:89
console.log(data);
^
ReferenceError: data is not defined
Data should be returning "test", but isn't. What am I doing wrong?
Your client should listen for the socket connection before attempting to emit to it:
var socket = io.connect("http://localhost:5678");
socket.on("newline", function(data) {
return $('#socketData').append('<li>' + data + '</li>');
});
socket.on("connect", function() {
socket.emit("pageReady", "test");
});
I'm just starting out with node.js, and from what I can tell so far, the way clients communicate with the server is through:
//Client Code 1
var iosocket = io.connect();
iosocket.on('connect', function () {
iosocket.send("Here's some info");
});
The server becomes aware of this when the 'message' event is recieved:
//Server Code 1
var socketio = require('socket.io');
var io = socketio.listen(server);
io.sockets.on('connection', function (client) {
client.on('message', function(msg) {
//msg== "Here's some info"
}
});
Now I want the client to be able to provide several distinct events such as:
//Server Code 2
client.on('buttonClicked', function() { ...
client.on('nameChanged', function(newName) { ...
But I'm having trouble figuring out how. The only solution I can come up with using the pieces I have is to send back messages, but have them contain key-value pairs of information:
//Server Code 3
client.on('message', function(msg) {
kvp = message.split(',');
if( kvp[0] == 'buttonClicked' )
...
else if( kvp[0] == 'nameChanged' )
...
}
But I'm certain there's a proper way of doing this that I just haven't seen in any examples yet. I expect that there's something similar to how the server can generate any event it wants using:
//Server Code 4
io.sockets.emit('serverCustomEvent', eventData);
Which are in turn monitored by the client using:
//Client Code 4
iosocket.on('serverCustomEvent', function(data) {
//process data
});
Can someone point me in the right direction?
You can use emit on the client to send custom messages to the server.
iosocket.emit('serverCustomEvent', data);
and on the server
io.sockets.on('connection', function(socket) {
socket.on('serverCustomEvent', login);
});
Messing around with socket.io just for proof of concept, everthing is working great so far except I can't get my emit callback to work on the client side. I've got to be missing something stupid here, but documentation is not killer at the moment. The server picks up the "getSomeData" event just fine, no errors anywhere.
From what I could tell in the client socket.io source, it checks if the last argument to emit is a function and always uses it as a callback, but debugging any deeper than that was problematic for me.
I feel like I have to be missing some core concept here..Is this not what this.send(..) is supposed to do? I could find only 1 useage in the example apps, and none where the client side code for that event emission was available.
Update: just to be clear, I am in fact intentionally emitting the event client side. The purpose of this was to see if socket.io could be used to allow clients to pull data on request in addition to receiving pushes.
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on("getSomeData", function() {
this.send({data: "some random data"});
});
});
client: (console.log never happens)
<script type="text/javascript" src="http://localhost/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://localhost');
socket.emit("getSomeData", function(data) {
console.log(data);
});
</script>
It looks like you have some logic switched around, try...
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit("getSomeData",{data: "some random data"});
});
and client...
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on("getSomeData", function(data) {
console.log(data);
});
</script>
EDIT:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on("getSomeData", function(name,fn) {
fn({data: "some random data"});
});
});
Client
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.emit("getSomeData", function(data) {
console.log(data);
});
</script>
In Liam William's answer, I found it was necessary to send the callback (or acknowledgement function) as the third argument on the client emit:
Client:
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.emit("getSomeData", null, function(data) {
console.log(data);
});
You can have the callback, but you have to do it a bit differently:
Server: (app.js)
var io = require('socket.io')(80);
io.on('connection', function (socket) {
// please note that server will take 2 data entries as function parameter below
socket.on('ferret', function (name, fn) {
fn('woot');
});
});
Client (index.html)
var socket = io(); // TIP: io() with no args does auto-discovery
socket.on('connect', function () {
socket.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
});
Actaully, socket io also mentions this one; sending-and-getting-data-(acknowledgements)