I am trying to understand dgram with a small example of client/server. However, it seems that I can only send 1 message per run of the client. If I try to send multiple messages like in below client code, nothing gets sent.
Server code:
var PORT = 16501;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
console.log('UDP Server: ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
console.log('Received: ' + remote.address + ':' + remote.port +' - ' + message);
});
server.bind(PORT, HOST);
Client code:
var PORT = 16501;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var i;
for(i=0;i<10;i++) {
client.send('Test Message', 0, 12, PORT, HOST, function(err, bytes) {
if (err) throw err;
console.log('Send: ' + HOST +':'+ PORT);
});
}
client.close();
This client code works but can only send 1 message.
var PORT = 16501;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
client.send('Test Message', 0, 12, PORT, HOST, function(err, bytes) {
if (err) throw err;
console.log('Send: ' + HOST +':'+ PORT);
client.close();
});
How can I make it so that it can send packets one after the other continuously?
You are closing the socket connection before the operations ends. I can suggest a flag to close it only after all the messages was sent, something like:
var totalReq = 10;
for (var i = 0; i < totalReq; i++) {
sendMessage(i, totalReq);
}
function sendMessage(index, total) {
client.send('Test Message', 0, 12, PORT, HOST, function(err, bytes) {
if (err) throw err;
console.log('Send: ' + HOST + ':' + PORT);
// close the connection only after the last request
if (index == total - 1) {
client.close();
}
});
}
Related
I can't seem to get the following communication working. Is it something to do with repl.it or am I just missing something?
client code - lua
local host, port = "test.abstractpoo.repl.co", 7865
local socket = require("socket")
local ip = assert(socket.dns.toip(host))
local udp = assert(socket.udp4())
assert(udp:setpeername(ip, port))
assert(udp:send("anything"))
server code - nodejs
var PORT = 7865;
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on("connect", function() {
console.log("client connected")
})
server.on('listening', function() {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ':' + address.port);
});
server.on('message', function(message, remote) {
console.log(remote.address + ':' + remote.port + ' - ' + message);
});
server.bind(PORT);
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 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');
});
I'm new to node.js, so forgive the ignorance if this is simple.
What I want to do is setup a simple node.js http server to which a web-client connects. I also want the node.js server to act as a UDP listener on a separate port, on which it will receive JSON payloads from some other application. I want the node.js server to then forward these JSON payloads immediately to one or more of the connected web-clients.
I got this far from some initial googling around:
Create a simple node.js http server that responds with a static html page:
//Initialize the HTTP server on port 8080, serve the index.html page
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
console.log('Listening at: 127.0.0.1 8080');
}
);
Initialize a UDP server on a separate port:
//Initialize a UDP server to listen for json payloads on port 3333
var srv = dgram.createSocket("udp4");
srv.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
io.sockets.broadcast.emit('message', 'test');
//stream.write(msg);
//socket.broadcast.emit('message',msg);
});
srv.on("listening", function () {
var address = srv.address();
console.log("server listening " + address.address + ":" + address.port);
});
srv.bind(5555);
Use socket.io to establish a live connection between web-client and server:
//this listens for socket messages from the client and broadcasts to all other clients
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg.data.skeletons[0] ? msg.data.skeletons[0].skeleton_id : '');
socket.broadcast.emit('message', msg);
}
);
});
I guess my problem is I don't know how to bridge 2 and 3, to get the received UDP packets broadcasted to the connected socket.io clients. Or perhaps there's a simpler, more elegant way of doing this? I found the documentation for socket.io to be lacking...
EDIT: thanks to the person that fixed the code formatting
I made a running example for you to get going with: http://runnable.com/UXsar5hEezgaAACJ
For now it's just a loopback client -> socket.io -> udp client -> udp server -> socket.io - > client.
here's the core of it:
var http = require('http');
var fs = require('fs');
var html = fs.readFileSync(__dirname + '/index.html');
//Initialize the HTTP server on port 8080, serve the index.html page
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end(html);
}).listen( process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP, function() {
console.log('Listening');
});
var io = require('socket.io').listen(server);
io.set('log level', 0);
io.sockets.on('connection', function (socket) {
socket.emit('message', 'connected');
socket.on('message', function (data) {
console.log(data);
var address = srv.address();
var client = dgram.createSocket("udp4");
var message = new Buffer(data);
client.send(message, 0, message.length, address.port, address.address, function(err, bytes) {
client.close();
});
});
});
var dgram = require('dgram');
//Initialize a UDP server to listen for json payloads on port 3333
var srv = dgram.createSocket("udp4");
srv.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
io.sockets.emit('message', 'udp');
});
srv.on("listening", function () {
var address = srv.address();
console.log("server listening " + address.address + ":" + address.port);
});
srv.on('error', function (err) {
console.error(err);
process.exit(0);
});
srv.bind();
I have created a TCP server using Node.js which listens to clients connections.
I need to transmit data from TCP server to HTTP server again in Node.js possibly through a Websocket (socket.io).
However, I do not know how to create such connection such that TCP server is able to push data to HTTP server through Websocket.
Many Thanks.
I was trying lot of things to get this work. Most of the time I was relying on socket.io to get this working, but it was just not working with TCP.
However, net.Socket suffices the purpose.
Here is the working example of it.
TCP Server
var net = require('net');
var HOST = 'localhost';
var PORT = 4040;
var server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.write("TCP sending message : 1");
console.log('Server listening on ' + server.address().address +':'+
server.address().port);
}).listen(PORT, HOST);
HTTP Server
var http = require('http').createServer(httpHandler),
fs = require("fs"),
wsock = require('socket.io').listen(http),
tcpsock = require('net');
var http_port = 8888;
var tcp_HOST = 'localhost';
var tcp_PORT = 4040;
/**
* http server
*/
function httpHandler (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);
});
}
http.listen(http_port);
console.info("HTTP server listening on " + http_port);
wsock.sockets.on('connection', function (socket) {
var tcpClient = new tcpsock.Socket();
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
tcpClient.connect(tcp_PORT, tcp_HOST, function() {
console.info('CONNECTED TO : ' + tcp_HOST + ':' + tcp_PORT);
tcpClient.on('data', function(data) {
console.log('DATA: ' + data);
socket.emit("httpServer", data);
});
tcpClient.on('end', function(data) {
console.log('END DATA : ' + data);
});
});
socket.on('tcp-manager', function(message) {
console.log('"tcp" : ' + message);
return;
});
socket.emit("httpServer", "Initial Data");
});
Browser Client
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('httpServer', function (data) {
console.log(data);
document.write(data + "\r\n");
socket.emit('tcp', "For TCP");
});
</script>
This way, there is a socket opened between HTTP server and TCP server in Node.js.
If you need to communicate server-server than websockets is probably not a best choice. Try one of RPC libraries, or just use HTTP or your own protocol.
You can use either socket.io or ws (only WebSocket) on Node.js as client (not only in browser)
var io = require('socket.io-client');
var socket = io.connect('http://IP address of Websocket server');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});