method client.write() doesn't work on simple server Node.js, - node.js

Could anybody say why server doesn't display "hello" from client.write("hello") ?
Thank you a lot!
server:
var net = require('net');
var server = net.createServer(function(client) {console.log('new client s')});
server.listen(2345,function(){console.log('opened server on ',2345)});
client:
var net = require('net');
var client = net.connect({port: 2345, host:'localhost'},function(){
console.log('connected to server!');
client.write("hello");
});

Server is not displaying because you have not handled what to do on recieving data from client :
For server:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 2345;
net.createServer(function(client) {
client.on('data', function(data) {
console.log('DATA ' + client.remoteAddress + ': ' + data);
client.write (data);
});
client.on('close', function(data) {
console.log('CLOSED: ' + client.remoteAddress +' '+ client.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
for client:
var net = require('net');
var client = net.connect(2345,'127.0.0.1',function(){
console.log('connected to server!');
client.write("hello");
});
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 2345;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('Hello');
});

Related

End of communication tcp server nodejs

Knowing that TCP is a stream based protocol, in the following example of a client server in nodejs what is telling the server that the client has finished sending all data?
Server
var net = require('net');
var server = net.createServer(function(socket) {
var remoteAddress = socket.remoteAddress + ':' + socket.remotePort;
console.log('new client connected: %s', remoteAddress);
socket.write('Echo server');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
client
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
for ( var i=0 ; i<100; i++) {
// console.log(i);
client.write('Hello, server! Love, Client.\r\n');
}
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
Thanks

Can't create socket server from http module

I wanna create socket server like a Socket.io because socket.io can't work with Corona SDK. So I need custom socket server. I create socket server with using net module and it is work good. But I need using http module because I write REST API. I try create sample socket server from http module but have errors.
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
var server = require('http').createServer(function(request, response) {
response.end('Hello from server');
});
server.on('connection', function(socket) {
socket.on('data', function(data) {
data = data.toString('utf-8');
console.log(data);
socket.write('Hello from server');
});
socket.on('error', function(error) {
console.log(error);
});
});
server.listen(PORT, HOST);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
If I run this script I got error:
CONNECTED TO: localhost:9999
I am Chuck Norris!
Error: This socket is closed
at Socket._writeGeneric (net.js:692:19)
at Socket._write (net.js:743:8)
at doWrite (_stream_writable.js:329:12)
at writeOrBuffer (_stream_writable.js:315:5)
at Socket.Writable.write (_stream_writable.js:241:11)
at Socket.write (net.js:670:40)
at Socket.<anonymous> (/var/work/projects/edorium/Server/test/test.js:49:16)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
{ Error: Parse Error
at socketOnData (_http_server.js:411:20)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (_stream_readable.js:136:10)
at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Connection closed
Why this happed and how fix this?
Additional to answer
I add HTTP headers to request and all works good!
Code sample below:
var http = require('http');
var net = require('net');
var express = require('express');
var HOST = 'localhost';
var PORT = 9999;
var app = express();
var server = http.Server(app);
app.get('/', function (req, res) {
res.send('Hello World!fff');
});
server.listen(PORT, HOST);
server.on('connection', function(socket) {
socket.on('data', function(data) {
data = data.toString('utf-8');
console.log(data);
socket.write('Hello from server');
});
socket.on('error', function(error) {
console.log(error);
});
socket.on('end', function() {
console.log('Socket end');
});
});
// Client
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
var messagae = '' +
'GET /' +
'Host:localhost:9999' +
'Content-Type:text/plain;charset=windows-1251' +
'Content-Length:6' +
'Connection:Keep-Alive;' +
'Hello!';
client.write(messagae);
});
client.on('data', function(data) {
console.log('DATA: ' + data);
});
client.on('close', function() {
console.log('Connection closed');
});
at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Since you have explicitly created a HTTP server this server is expecting a HTTP request. But you are just sending "I am Chuck Norris!" which is definitely not a HTTP request. Therefore the server closes the connection.
To send a HTTP request you might use http.request. Alternatively you can study the HTTP standard and build a proper HTTP request yourself.
Your client was disconnect
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.on('data', function(data){
console.log(data);
textChunk = data.toString('utf8');
console.log(textChunk);
socket.write("================");
});
});
server.listen(PORT, '127.0.0.1');
server.listen(PORT, HOST);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
var i = 0;
client.on('data', function(data) {
console.log('Received: ' + data);
i++;
if(i==2)
client.destroy();
} );
client.on('close', function() {
console.log('Connection closed');
});

Communication between Nodejs http server and net server

In here I have a http server and a net server on the same file. The net server connects to Arduino. I want to show the data received from Arduino on the http server website. Also when a button is pressed on the website, I want to send some data through the net server to the arduino. How can I do that.
var http = require("http");
var url = require('url');
var fs = require('fs');
var ip = require('ip');
var net = require('net');
var colors = require('colors');
var formidable = require('formidable');
var HOST = ip.address();//my IP address
var HTTP_PORT = 4321;
var NET_PORT = 1234;
var NAME;
var backButton;
var _p1 = '<form role="form" action="enext" method="post" enctype="multipart/form-data">'
+ '<h1>'
+ '=== Arduino Data Online ==='
+ '</h1><br><h2>'
+ 'Arduino data: ';
var _msg = 'sock data';
var _p2 = '</h2><br><br>'
+ '<h3>'
+ 'Press NEXT after fp success'
+ '</h3><br><b>'
+ '<button type="submit">'
+ 'NEXT'
+ '</button></form>';
//socket
function func(sock) {
console.log(colors.cyan('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort));
// Add a 'data' event handler to this instance of socket
sock.on('data', function (data) {
////========
console.log(data);
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function (data) {
console.log(colors.cyan('CLOSED: ' + sock.remoteAddress + ' ' + sock.remoteNET_PORT));
console.log("");
httpserver.close();
});
sock.on('error', function (data) {
console.log(colors.magenta("clnt error"));
httpserver.close();
});
}
net.createServer(func).listen(NET_PORT, HOST);
console.log(colors.yellow('Server listening on ' + HOST + ':' + NET_PORT));
var httpserver = http.createServer(function (request, response) {
var path = url.parse(request.url).pathname;
console.log('CONNECTED');
console.log(path);
switch (path) {
case '/':
response.writeHead(200, { "Content-Type": "text/html" });
response.write(_p1, "utf8");
response.write(_msg, "utf8");
response.write(_p2, "utf8");
response.end();
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
httpserver.listen(HTTP_PORT, HOST);
console.log('http://Server # ' + HOST + ':' + HTTP_PORT);

socket.io with node cluster only long poll works

Using socket.io and nodeJS cluster, looks like Websocket protocol fails and it falls back to long polling, any idea why it isnt using websocket?
This is the only error in console
WebSocket connection to
'ws://localhost:5050/socket.io/?EIO=3&transport=websocket&sid=82qh7nBXGusxyelJAAAG'
failed: Connection closed before receiving a handshake response
Here is my node application
if (cluster.isMaster) {
// we create a HTTP server, but we do not use listen
// that way, we have a socket.io server that doesn't accept connections
var server = require('http').createServer();
var io = require('socket.io').listen(server);
var redis = require('socket.io-redis');
var fs = require('fs');
io.adapter(redis({host: '127.0.0.1', port: 6379}));
var i = 0;
setInterval(function () {
// all workers will receive this in Redis, and emit
io.sockets.in('EURUSD').emit('message', 'EURUSD ' + i++);
io.sockets.in('GBPUSD').emit('message', 'GBPUSD ' + i++);
}, 1000);
for (var i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log("New Worker with ID ", worker.id);
});
cluster.on('exit', function (worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
}
if (cluster.isWorker) {
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(config.port);
var io = require('socket.io').listen(server);
var redis = require('socket.io-redis');
io.adapter(redis({host: '127.0.0.1', port: 6379}));
io.sockets.on('connection', function (socket) {
console.log('connected to worker id ', cluster.worker.id);
socket.on('join', function (room) {
socket.join(room);
});
});
app.get("/", function (req, res) {
res.sendFile('views/index.html', {root: __dirname});
});
}
Client code
var socket = io();
socket.on('message', function (data) {
var item = $('<li>' + data + '</li>');
$('ul').prepend(item);
});
socket.emit("join", "GBPUSD");
For those who may face similar issue, it turned out that I have the following line twice
var io = require('socket.io')(server);
Removing one, solved the issue.

Creating a chat with nodejs ws (einaros)

Yesterday I started using this module. I'm trying to make a chat for do something with websockets.
I have the problem, that I don't know how to pass the message that sends a client to the server for then show it for all users. In the server side I have this code:
var ipaddress = 'localhost';
var port = 8080;
var WebSocketServer = require('ws').Server
, ws = new WebSocketServer({host:ipaddress, port:port});
ws.on('connection', function(ws) {
console.log('New connection');
ws.on('message', function(message) {
ws.send(message);
});
});
console.log('Listening to ' + ipaddress + ':' + port + ' ...');
And in the client side this other code:
jQuery(document).ready(function($) {
var content = $('#screen');
var message = $('input[type="text"]').val();
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function() {
console.log('Connected');
};
$('input[type="button"]').click(function() {
ws.send(message);
});
ws.onmessage = function(msg) {
console.log('Received message from server: ' + msg.data);
addMessage(msg.data);
}
function addMessage(message) {
content.prepend('<p><span>' + message + '</span></p>');
}
});
It's explained here:
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({host:ipaddress, port:port});
wss.broadcast = function(data) {
for (var i in this.clients)
this.clients[i].send(data);
};
// use like this:
wss.on('connection', function(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
});
});
var WebSocketServer = require('ws').Server
var webserver = new WebSocketServer({ port:3000 });
webserver.on("message",function(message) {
webserver.clients.forEach(function(client) {
client.send(message);
});
}):

Resources