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);
Related
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?
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();
}
});
}
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'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();
Apparently, I am testing out simple TCP server that uses Node.js.
The server code, and the client code works well if they are both on the same machine.
However, it seems that when I run the server on the different machine and test to connect to the server from the client in different machine, I get error like below.
Error: connect ECONNREFUSED
at errnoException (net.js:589:11)
at Object.afterConnect [as oncomplete] (net.js:580:18)
I tried by typing IP address of the server, or the domain name of the server, but no luck.
The server code is like below, (server was ran with root privilege..)
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('You said "' + data + '"');
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
and the client code is like below
var net = require('net');
var HOST = '127.0.0.1'; //I set it to server IP address but no luck..
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');
});
Is there any configuration that I have to go through, if I want the server to accept socket connections from different machine? Do I have to run server code as production mode (if there is such mode)?? Or, is there limitation in port range?
Set the server to bind to 0.0.0.0 and set the client to connect to the correct IP address of the server. If the server is listening on 127.0.0.1, it will only accept connections from its local host.