I'm trying to build a simple Node app using Express, Socket.io, and the ntwitter module so you can just search for a term (that's req.params.searchTerm below) and ntwitter will search for it and output the stream via socket.io.
I'm running into errors, though, with multiple windows open, or closing a window and then opening a window immediately afterwards. Sometimes the search term is not updated, sometimes some kind of socket.io error is actually thrown. Could someone clarify the right way to do this or shed some light to my error? Thanks in advance. Code below.
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
app.get('/:stream', function(req, res) {
res.render('stream', { title: 'Search Twitter | ' + req.params.searchTerm });
io.sockets.on('connection', function(socket) {
var publishFlag = true;
setInterval(function() {
publishFlag = true;
}, 1000);
twit.stream('statuses/filter', { track: [req.params.searchTerm] },
function(stream) {
stream.on('data', function(tweet) {
if(publishFlag) {
socket.emit('tweet', tweet);
publishFlag = false;
}
});
}
);
});
});
It think that is somewhat what you are trying to do :
Server side :
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
app.get('/:stream', function(req, res) {
res.render('stream', { title: 'Search Twitter | ' + req.params.searchTerm });
});
io.sockets.on('connection', function(socket) {
socket.on('stream', function(searchTerm){
twit.stream('statuses/filter', { track: [searchTerm] },
function(stream) {
stream.on('data', function(tweet) {
socket.emit('tweet', tweet);
});
}
);
};
});
client side (/:stream)
var socket = io.connect('http://localhost');
socket.on('tweet', addTweetOnPage);
socket.emit('stream', searchTerm);
Related
Node js net module server code:
var net = require('net');
var server = net.createServer(function (connection) {
console.log('client connected');
connection.on('data', function (data) {
console.log('data from flash = ' + data);
var jsonData = {};
jsonData.message = "joined";
var d = JSON.stringify(jsonData);
connection.write(d);
});
connection.on('end', function () {
console.log('client disconnected');
});
// connection.pipe(connection);
});
server.listen(3055, function () {
console.log('server is listening');
});
Action script code
this.login_socket.connect(this.server_ip,3055);
this.login_socket.addEventListener(Event.CONNECT,this.login_socket_onConnection);
this.login_socket.addEventListener(DataEvent.DATA,this.login_onData);
this.login_socket.addEventListener(IOErrorEvent.IO_ERROR,this.login_socket_onIOErrorEvent);
this.login_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,this.login_socket_SecurityErrorEvent);
this.login_socket.addEventListener(Event.CLOSE,this.login_socket_closeErrorEvent);
Can anyone please tell me how to use xml socket with node js net module? I have tried everything but this doesn't work at all. I want to create a socket connection for a flash game to the server. I am using laravel as backend. If anyone knows how to create it with php tell me. Thank you.
var net = require('net');
var server = net.createServer(function (connection) {
console.log('client connected');
connection.setEncoding("utf8");
// on receive data from client
connection.on('data', function (data) {
console.log('data from flash = ' + data);
var d = JSON.stringify({
message: "joined"
}) + "\0";
connection.write(d);
});
// on connection end
connection.on('end', function () {
console.log('client disconnected');
});
// on error
connection.on("error", function (exception) {
console.log('an error occurred: ' + exception);
});
});
server.listen(3055, function () {
console.log('server is listening');
});
I change nodejs server code to above code and it works fine now.
I'm listening all the connections from a GPS device who is send the data to a our server. So I create a small NodeJs app to retrieve that information.
var net = require('net');
var server = net.createServer(function(connection) {
connection.on('drain', function(){
console.log('drain');
});
connection.on('data', function(data){
var dataGps = data.toString('ascii');
var fecha = new Date();
console.log(String(fecha));
var dataArray = dataGps.split(',');
});
connection.on('end', function() {
//console.log('Client disconnected'.magenta);
});
connection.on('error', function(err) {
//console.log("Connection error: " + err+" ... ".red);
//console.log('Closing connection....'.red);
//connection.destroy();
});
connection.on('close', function(){
console.log('closed event fired');
});
});
server.on('connection', function(){
console.log('new connection');
});
server.getConnections(function(err, count){
if (err) {
console.log('# Error: '+err);
}
console.log('Count: '+count);
});
server.listen(3001, function() {
console.log('Server is listening on port 3001...');
});
To keep running this App, I'm using pm2 (pm2 website).
Everything is fine except that sometimes this app becomes inactive and don't do anything until I restart it with pm2.
This app is in Amazon EC2 (t2.medium instance) Ubuntu 16.04.
I don't know what I'm doing wrong. Any help would be really helpful.
I'm currently trying to have an angular2 frontend communicating with a node.js backend with socket.io.
The point is, I get the client connected to the server, but after that, no socket call can be successfully passed between them.
Here is a simple piece a code for the server :
var app = require('express')();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.on('connection', function() {
io.emit('update');
console.log('Connected');
});
io.on('updated', function() {
io.emit('update');
console.log('Updated');
});
server.listen(5000, function() {
console.log('Listening on 5000');
});
... and for the component :
import { Component } from '#angular/core';
import * as io from 'socket.io-client';
#Component({
selector: 'main-app',
template: `
<div>
<button (click)="foo()"
style='padding:20px; background:red; color:white'>
click me
</button>
</div>
`
})
export class AppComponent {
title = 'bar';
socket = null;
constructor() {
let self = this;
self.socket = io.connect('http://mysuperwebsite:5000', {
transports : ["websocket"]
});
self.socket.on('update', function(data) {
console.log(data);
});
}
foo() {
let self = this;
self.socket.emit('updated', {});
}
}
I can't get what is wrong, I guess you will ;)
Thanks for your help !
EDIT : Finally, the problem seemed to come from the lack of second parameter in io.emit(). Now it works, thanks you very much :)
Instead of debugging your code, I'll post you an example that works and you can go from there:
Socket.IO Server
Socket.IO server example using Express.js:
var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
console.error('express connection');
res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
console.error('socket.io connection');
for (var t = 0; t < 3; t++)
setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
console.error('socket.io example');
Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js
Socket.IO Client
Socket.IO client example using vanilla JavaScript:
var l = document.getElementById('l');
var log = function (m) {
var i = document.createElement('li');
i.innerText = new Date().toISOString()+' '+m;
l.appendChild(i);
}
log('opening socket.io connection');
var s = io();
s.on('connect_error', function (m) { log("error"); });
s.on('connect', function (m) { log("socket.io connection open"); });
s.on('message', function (m) { log(m); });
Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.html
That example can be installed from npm or downloaded from GitHub. It's as simple as it gets and it's known to work so you can have a working backend part to test your frontend with.
It was written for this answer - you can find mush more info there.
Your server setup seems to be incorrect.
Try this:
io.on('connection', function(socket) {
socket.emit('update');
console.log('Connected');
socket.on('updated', function() {
socket.emit('update');
console.log('Updated');
});
});
I've found this script for reading a file an "broadcast" its content to every connection.
var serverServiceConfig={port: 8081};
var express = require("express");
var app = express();
var fs = require('fs');
var socket = require('socket.io');
function readTick(ws){
fs.readFile('tick.json', 'utf8', function (err,data) {
if (!err) {
try {
ws.emit('ticks', data);
} catch (e) {
// handle error
console.log('can not read file');
}
}
});
setTimeout(function () {
readTick(ws);
}, 200);
}
console.log('server is running ...');
app.configure(function(){
app.use(express.static(__dirname + '/'));
});
var server = app.listen(serverServiceConfig.port);
var io = socket.listen(server);
io.sockets.on('connection', function (socket) {
readTick(socket);
socket.on('disconnect', function (socket) {
});
});
The server starts without an error, so far so good. But if i try to connect to the server via ip:port i get the following message:
Cannot GET /
I tested this script on my local machine and it worked (a couple of weeks ago)
From what i "know" or i think is that a route is missing, or?
Any help is more than welcome.
Thank you in advance
Instead of using that function, you should put it in app.get('/', function(){//whatever you want to do//})
I have a socket.io server running and a matching webpage with a socket.io.js client. All works fine.
But, I am wondering if it is possible, on another machine, to run a separate node.js application which would act as a client and connect to the mentioned socket.io server?
That should be possible using Socket.IO-client: https://github.com/LearnBoost/socket.io-client
Adding in example for solution given earlier. By using socket.io-client https://github.com/socketio/socket.io-client
Client Side:
//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {reconnect: true});
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');
Server Side :
//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function (socket){
console.log('connection');
socket.on('CH01', function (from, msg) {
console.log('MSG', from, ' saying ', msg);
});
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
Run :
Open 2 console and run node server.js and node client.js
After installing socket.io-client:
npm install socket.io-client
This is how the client code looks like:
var io = require('socket.io-client'),
socket = io.connect('http://localhost', {
port: 1337,
reconnect: true
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });
Thanks alessioalex.
const io = require('socket.io-client');
const socket_url = "http://localhost:8081";
let socket = io.connect(socket_url);
socket.on('connect', function () {
socket.emit("event_name", {});
});
Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.
Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
socket.on('connect', (data) => {
console.log('Connected to Socket');
});
socket.on('event_name', (data) => {
console.log("-----------------received event data from the socket io server");
});
//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect again with server");
}
// else the socket will automatically try to reconnect
});
socket.on('error', (error) => {
console.log(error);
});
something like this worked for me
const WebSocket = require('ws');
const ccStreamer = new WebSocket('wss://somthing.com');
ccStreamer.on('open', function open() {
var subRequest = {
"action": "SubAdd",
"subs": [""]
};
ccStreamer.send(JSON.stringify(subRequest));
});
ccStreamer.on('message', function incoming(data) {
console.log(data);
});