I am very new to nodejs and I have some client-server implementation, which basically works the following manner : I submit a form which throws data to a client remote server. The latter send me back some new data.
net.createServer(function (socket) {
socket.on('error',function(err){ console.error(err)});
socket.on('data', function (data) {
some_method(data)
});
socket.on('end', function() {
console.log('CONN: disconnected');
//socket.end();
});
app.post('/api/sender', function(req, res) {
socket.write(some_input);
res.end();
});
}).listen(9000);
This works well until the client disconnects itself and reconnects, then I get the following error message :
{ [Error: This socket has been ended by the other party] code: 'EPIPE' }
And the code crashes at this line socket.write(some_input). Can someone can help ?
here's how this could be tackled :
module.exports = function(app) {
var clients = {};
var server = net.createServer(function (socket) {
server.getConnections(function(err, count) {
var id = sha1(socket.remoteAddress);
clients[id] = {
stream: through(),
socket: socket,
}
clients[id].stream.pipe(socket);
});
socket.on('error',function(err){ console.error(err)});
socket.on('data', function (data) {
some_method(data)
});
socket.on('end', function() {
console.log('CONN: disconnected');
socket.end();
});
app.post('/api/sender', function(req, res) {
// here id is the IP adress got from req
if (clients[id]) {
clients[id].stream.write(input);
}
res.end();
});
}).listen(9000);
};
Related
I am making a real-time Lumen API. For that i have used Node.js to create the server.
It works perfectly fine on localhost, but not when published
This is the code for my Node Server.js
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();
app.listen(6001, function() {
console.log('Server chalu hua');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
console.log('Lijiye Nya connection bna diya gya');
});
io.on('disconnect', function(socket) {
console.log('Connection Dropped');
});
redis.psubscribe('*', function(err, count) {
//
});
redis.on('pmessage', function(subscribed, channel, message) {
console.log(channel);
message = JSON.parse(message);
console.log(message);
io.emit(channel, message.data);
})
Can someone tell what to do, to make it work in Production
created index.js (server)
var express = require('express');
var app = express();
///creating server
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, { origins:'http://nodejs-atnodejs.rhcloud.com:8000' });
below is remaining code
Routing to index.html page
app.get('/', function (req, res) {
console.log('in socket---' + res);
res.sendfile('index.html');
});
///socket connection
io.sockets.on('connection', function (socket) {
socket.on('chatmessage', function (msg) {
io.emit('chatmessage', msg);
console.log('in socket---' + data);
});
});
/// Listen to Openshift port
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
created index.html(client)
src="http://nodejs-atnodejs.rhcloud.com:8000/socket.io/socket.io.js
var socket = io.connect('http://nodejs-atnodejs.rhcloud.com:8000');
console.log('this is index page');
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
socket.emit('chatmessage', { my: 'data' });
});
When accessed from browser:
Problem is not getting "console.log('chatmessage---' + data);" which is inside the socket..
and keep on getting xhr-polling../t=xxxxx responses..
is my socket working properly?
Both your browser and server code is listening for an event of 'chatmessage' after connection either your browser or server should be emitting the event first and than the other should be listening such as...
// server
io.sockets.on('connection', function (socket) {
socket.emit('chatmessage', /*some data*/);
});
//client
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
});
Events binding for socket are moved to separate module:
exports.bind = function(socket) {
socket.on('join', function(data) {
socket.join(data.type);
});
socket.on('message', function(data) {
global.io.sockets.in('rooma').emit('message', data);
});
}
server.js:
var app = express();
//creating socket server
server = http.createServer(app);
io = global.io = require('socket.io').listen(server, {'log level': 3});
io.sockets.on('connection', function(socket) {
//binding events on socket
events.bind(socket, io);
});
The problem is, that message is never sent to the clients in 'rooma'. But if i emit it global:
global.io.sockets.emit('message', data);
It works. Where can be problem? I've tested the client belongs to room for sure.
this works when you get the initialisation of the event from the room to which you like to send your message:
exports.bind = function(socket) {
socket.on('join', function(data) {
socket.join(data.type);
});
socket.on('message', function(data) {
socket.get('room', function (error, room) {
io.sockets.in(room).emit('message', data);
});
});
}
I'm working on a simple Node.js bi-directional client\server communication channel and I'm attempting to use socket.io on the server and socket.io-client on the client.
I've inserted the code below, as you'll see it's pretty basic stuff, and I'm running both on my local machine - to minimise complexity.
The behaviour I'm seeing is:
I start the server.
The server logs 'Server started' to the console.
I start the client.
The client logs 'Server is ready!'
Nothing else happens...
What I'd expect is the server to log a 'Client is ready!' message and then the content ('Ready received').
I've even used WireShark to sniff the line and it does appear that the client is emitting the message, as designed - but the callback on the server isn't firing.
I'm running node v0.8.4 with express v3.1.0, socket.io v0.9.13 and socket.io-client v0.9.11 (all installed via npm).
Here's the server code...
var http = require('http'),
express = require('express'),
app = express(),
server = http.createServer(app);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
server.listen(8080);
console.log("Server started");
var io = require('socket.io').listen(server);
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
And here's the client code...
var clientio = require('socket.io-client');
var socket = new clientio.connect('http://localhost', { port: 8080 });
socket
.on('server ready', function(data){
console.log('Server is ready!');
socket.emit('comms', 'Ready received');
})
.on('connect-error', function(error) {
console.log('Connection Error\n' + error);
})
.on('error', function(error) {
console.log('Socket Error\n' + error);
})
The documentation and examples for both socket.io and socket.io-client are somewhat confused (to be charitable) and they appear to be a bit of a moving target... but from what I can tell, I think this should work.
I'm hoping someone can give me advice as to where I'm going wrong?
In your server you have this code:
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
What you should do is something like this:
io.sockets.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' });
socket.on('comm', function(content){
console.log('Client is ready!');
console.log(content);
});
});
hopefully this is doing more or less what you need it to do. Just a couple of minor changes.
app.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
// using 'connect' to handle static pages
app.use(require('connect').static(__dirname + '/public'))
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('server ready', { msg: 'ready' });
socket.on('comms', function(content) {
console.log(('Client is ready\n'));
console.log(content);
});
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
window.jQuery || document.write('<script src="js/jquery-1.8.3.min.js"><\/script>')
</script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
(function (d, b) {
function bindEvents() {
function doSomething(msg) {
$.each(msg, function (key, value) {
console.log('doSomething...');
$("body").append("<p>" + value + "</p>")
});
};
// var socket = io.connect();
var socket = io.connect('http://localhost');
socket.on('server ready', function (msg) {
console.log('Server is ready!\n', msg);
doSomething(msg);
socket.emit('comms', {
msg: 'Client is Ready'
});
});
socket.on('connect-error', function (err) {
console.log('Connection Error\n', err);
});
socket.on('error', function (err) {
console.log('Connection Error\n', err);
});
};
$(document).ready(function () {
bindEvents()
});
})(jQuery, this)
</script>
I'm trying an example of WebSocket to develop a simple chat.
server.js:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/test.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
and test.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('connect', function() {
alert('<li>Connected to the server.</li>');
});
socket.on('message', function(message) {
alert(message);
});
socket.on('disconnect', function() {
alert('<li>Disconnected from the server.</li>');
});
function sendF(){
var message = "Test";
socket.send(message);
alert('Test Send');
}
In test.html I have also a simple button that onClick call sendF.
If I try it I see on my browser an alert when I CONNECT, SEND, and DISCONNCT, and if I check in console, I see the message.
But I cannot receive the same message in response from server, to show it in my browser! I think socket.on('message'... is not working for me!
Your server.js is missing event listeners. It's also missing where you are doing the send of the message to be displayed in the browser.
io.sockets.on('connection', function (socket) {
console.log('user connected');
socket.send('hello world');
socket.on('disconnect', function () {
console.log('user disconnected.');
});
socket.on('message', function (data) {
console.log(data);
});
});