I connected through this nodejs code using telnet. When exiting from telnet, the 'end' event fires but does not show the remote address and port.
var net = require('net');
var server = net.createServer(function(s) {
console.log('CONNECT:' + s.remoteAddress + ':' + s.remotePort);
s.on('data', function(data) {
console.log('DATA: ' + s.remoteAddress + ':' + s.remotePort);
s.write('You said "' + data + '"');
});
s.on('end', function() {
console.log('END: ' + s.remoteAddress + ':' + s.remotePort);
});
s.write('hello\r\n');
});
server.listen(8000, function() {
console.log('Server started on port 8000');
});
On the server console, i get the following when I quit telnet
END: undefined:undefined disconnected
Any ideas?
The end event is fired when the client has closed the connection. In that case, the default behaviour for net.createServer is to also close the connection (but see below), so there is no more remoteAddress and remotePort at the time your callback is called.
The easiest solution is to just store those values in a variable when the connection is created:
var server = net.createServer(function(s) {
var address = s.remoteAddress;
var port = s.remotePort;
...
s.on('end', function() {
console.log('END: ' + address + ':' + port);
});
});
Another option is to enable allowHalfOpen, which will stop the server from closing the connection when the client has closed their side:
var server = net.createServer({ allowHalfOpen : true }, function(s) {
...
s.on('end', function() {
console.log('END: ' + s.remoteAddress + ':' + s.remotePort);
s.end(); // !!! close the server side explicitly
});
});
Related
I am just trying to learn some client-server basics and I'm almost there with what I'm trying to do. I am just sending the server some input and having it respond back to the client with the data it received. However, it works fine once I send the first piece of data but once I send another input the server responds with two instances of that same piece of data, and so on. How do I get around this?
Server:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
var server = net.createServer();
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress +':' + data);
// write back data received to the client
sock.write('You said "' + data + '"');
});
});
server.listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
Client:
var net = require('net');
var readline = require('readline');
var HOST = '127.0.0.1';
var PORT = 6969;
const r1 = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// continue talkback
function waitForUserInput() {
r1.question("Enter some data you wish to send: ", function(data) {
if(data == "exit") {
r1.close();
} else {
// write input data to the server
client.write(data);
// receive what data server sends back to client
client.on('data', function(server_data) {
console.log('DATA: ' + server_data);
});
setInterval(waitForUserInput, 1000);
}
});
}
waitForUserInput();
});
You keep adding more and more client.on('data', ...) handlers. Each time you call waitForUserInput(), you end up adding another duplicate handler for the data message. So, after calling waitForUserInput() twice, you have two identical handlers for the data message so when a new piece of data arrives, each of the two handlers gets called and the output in your console appears twice. One one piece of data arrives, but you have duplicate handlers that are listening for it.
You can either use .once() instead of .one() or you can move the handler listening for the incoming data outside of the function so it's just installed once and only once.
Incidentally, using setInterval() here is also a problem for several reasons. You're creating a new interval timer every time you call waitForUserInput() and there's no coordination between that and when the question is actually answered.
I'm writing a simple chat app using Node.js. The server-side code is :
const net = require('net');
const HOST = 'localhost';
const PORT = 3000;
const server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', (socket) => {
console.log(socket.localPort);
console.log(socket.remotePort);
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
socket.on('data', (data) => {
console.log('DATA ' + socket.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
socket.write('You said "' + data + '"');
});
socket.on('close', () => {
console.log('CLOSED: ' + socket.remoteAddress +' '+ socket.remotePort);
});
socket.on('error', () => {
console.log('ERROR OCCURED:');
});
});
console.log('Server listening on ' + HOST +':'+ PORT);
The problem is that, when a client connects to the server, the socket object is UNIQUE every time a client connects, so the different clients cannot exchange messages.
How I can make different users connect to same socket so they can exchange messages?
Am trying to post some string from my tcp client to tcp server(Both were implemented using NodeJS). Once I receive message from client I need to write some integer value in the same socket. But when I tried writing the integer value, am getting an exception saying "Invalid Data". Can you please help me to understand or fix this.
Server Code:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
sock.write(data.length);
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
Client Code
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
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');
});
Output:
CONNECTED: 127.0.0.1:56183 DATA 127.0.0.1: I am Chuck Norris!
net.js:612
throw new TypeError('invalid data');
Try this:
var writeBuffer = Buffer(1);
writeBuffer[0] = 1; //Value to send
.
.
client.write(writeBuffer);
The output says it all, invalid data!
request.write(chunk[, encoding][, callback])
The chunk argument should be a Buffer or a string.
sock is Stream, you can write Buffer or string into stream.
You should read the documentation of nodejs here https://nodejs.org/api/http.html#http_request_write_chunk_encoding_callback
What are you trying to achieve, communication between processes?
I tried to test the function of setKeepAlive() in NodeJS. I ran Server.js and client.js on different machines within same local network. Then, I turned off the wifi connection on the client machine (break the internet connection). After 15 minutes, there is still no message thrown. Why is that? Didn't setKeepAlive() work?
Here is the code of the server and client:
Client.js
var net = require('net');
var HOST = '192.168.0.16';
var PORT = 8333;
var client = net.connect(PORT, HOST, function connected(){
console.log('connected');
});
client.setKeepAlive(true, 1);
client.write('hi server');
client.on('data', function(data) {
console.log('Received' + data);
});
client.on('close', function(){
console.error('connection closed');
)};
client.on('error', function(err){
console.error('error', err);
});
Server.js
var net = require('net');
var HOST = '192.168.0.16';
var PORT = 8333;
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
sock.write('hi client');
});
sock.on('close', function(data) {
console.log('CLOSED: ' +
sock.remoteAddress + ' ' + sock.remotePort);
});
sock.on('error', function(error){
console.log('error', error);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
I would implement keep_alive by myself using both setInterval(sendKeepAliceFunc, delay), and socket.setTimeout()
Delay between keep_alive message should be big enough (~10000ms), it not valid if delay < round trip (?)
I think the original keepalive feature is not reliable. I have success enable it on other programming language (C# and C) and I can trace network and see KEEP_ALIVE packets, but then it NOT work in some circumstances (special network configuration, people may run app in virtual machine, ...)
So I suggest implement it by yourself, you can implement a your own socket with the same APIs but also has your new keepalive feature.
I want connect to asterisk via socket programming how can i do this?
I know there are many module that we can use of these but i dont want use theme.
I read this page and want to know How can i connect to asterisk in Node.js via socket programming ?
This code is TCP Sample:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {
// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
sock.write('You said "' + data + '"');
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
Use this article:
We can use socket programming in node.This sample code is for connect via TCP.
var net = require('net');
var port = 5038;
var host = "IP";
var username = "User";
var password = "Pass";
var CRLF = "\r\n";
var END = "\r\n\r\n";
var client = new net.Socket();
client.connect(port, host, function () {
console.log('CONNECTED TO: ' + host + ':' + port);
var obj = { Action: 'Login', Username: username, Secret: password};
obj .ActionID =1;
var socketData = generateSocketData(obj);
console.log('DATA: ' + socketData);
client.write(socketData, 'ascii');
});
generateSocketData = function(obj) {
var str = '';
for (var i in obj) {
console.log('obj[i]:'+obj[i]);
str += (i + ': ' + obj[i] + CRLF);
}
return str + CRLF;
};
client.on('data', function (data) {
console.log('New Event Recived');
console.log('******************************');
console.log('DATA: ' + data);
});
client.on('close', function () {
console.log('Connection closed');
});