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
Related
I have implemented socket.io with node.js http server. The server pushes the Realtime data to the clients. I noticed a problem that when the server is restarted the client does not get data automatically means it does not reconnect automatically with the server. Please suggest the solution. My client code is as below
client index.html
<script>
var socket = io.connect('http://localhost');
socket.on('field', function (data) {
console.log(data); });
</script>
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8070);
var mysocket = 0;
function handler(req, res)
{
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('index.html connected');
mysocket = socket;
});
//udp server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("msg: " + msg);
if (mysocket != 0){
mysocket.emit('field', "" + msg);
}
});
server.on("listening", function () {
var address = server.address();
console.log("udp server listening " + address.address + ":" +
address.port);
});
server.bind(41181);
I have following code, As there are N number of socket sending sequential stream.
how to scale this using worker threads in nodejs.
const Net = require('net');
const port = 8080;
const server = new Net.Server();
const processor = require('processor.js');
server.listen(port, function() {
console.log(`Server listening for connection requests on socket localhost:${port}`.);
});
server.on('connection', function(socket) {
console.log('A new connection has been established.');
let connectionInfo = {};
connectionInfo.id = `${socket.remoteAddress}:${socket.remotePort}`;
connectionInfo.partialBuffer= undefined;
socket.on('data', function(chunk) {
let chunkBuffer = Buffer.from(chunk);
if(connectionInfo.partialBuffer){
chunkBuffer = Buffer.concat([connInfo.partialBuffer, chunkBuffer]);
}
processor.processChunk(connectionInfo, chunkBuffer); // set connectionInfo.partialBuffer in processChunk() function
});
socket.on('end', function() {
console.log('Closing connection with the client');
});
socket.on('error', function(err) {
console.log(`Error: ${err}`);
});
});
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');
});
I start create server with Nodejs and socket.io in simple way.
In client connect just fine but when emit pong to server it never show.
This code:
SERVER
var PORT = 3003;
var io = require('socket.io')(PORT);
var clients = [];
setInterval (function() {
io.sockets.emit('ping');
}, 3000);
io.on('connection', (function(socket) {
socket.emit ('welcome', { message: 'Connection complete', id: socket.id });
clients.push ({id: socket.id, clientSocket: socket});
print ('Client connected ' + socket.id);
socket.on('disconnect', function() {
clients.splice(clients.indexOf(socket), 1);
print (socket.id + " is disconnected.");
});
socket.on('pong', function(args) {
print (args + " is pong.");
});
}).bind(this));
print('Server starting ...');
CLIENT:
var PORT = 3003;
var io = require('socket.io-client');
var socket = io.connect('http://localhost:' + PORT);
socket.on('connect', function(){
print ('Client connected...');
});
socket.on('welcome', function(args) {
print (args.message + ' / ' + args.id);
// socket.disconnect();
});
socket.on ('ping', function(args) {
socket.emit ('pong', { id: socket.id });
print ('Receive ping...');
});
print ('Client Starting...');
I'm trying to send a string from Node.js to a Java server but nothing will send from the Node.js client unless I call client.end() after. I'm not very experienced with Node.js so any suggestions would help.
var net = require('net');
var client = net.connect(1032, 'localhost')
client.on('connect', function(){
console.log('connected');
});
client.on('data', function(data){
console.log(data.toString());
client.write('test reply');
});
client.on('close', function(){
client.end();
});
var net = require('net');
var client = net.connect(1032, 'localhost')
client.on('connect', function(){
console.log('connected');
client.write('test reply');
});
client.on('data', function(data){
console.log(data.toString());
});
client.on('close', function(){
client.end();
});