UDP socket in node.js - javascript

I am trying to connect to an UDP socket on another computer using the UDP socket of node.js and I am getting the following error:
bind EADDRNOTAVAIL192.168.1.50;12345
I am using the following code:
var port = 12345;
var host = "192.168.1.50";
var sock = dgram.createSocket("udp4");
sock.on("listening", function () {
console.log("server listening ");
});
sock.on("error", function (err) {
console.log("server error:\n" + err.stack);
sock.close();
});
//start the UDP server with the radar port 12345
sock.bind(port, host);
any help?
thanks

You can't bind to the remote server address! It doesn't matter what your server ip is, you should bind to one of your local interfaces. If you want to bind on all local interfaces, just bind like following:
sock.bind(port);

You can send UDP datagrams in the following way (Sample code)
var dgram = require('dgram');
var PORT = 12345;
var HOST = '192.168.1.50';
var message = new Buffer('Pinging');
var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
if (err) throw err;
console.log('UDP message sent to ' + HOST +':'+ PORT);
client.close();
});
Reference: http://www.hacksparrow.com/node-js-udp-server-and-client-example.html

Related

How to use sockets to send information from javascript to python

I want to send information from my Node.js code to Python using sockets. How can I achieve that?
In pseudo-code, what I want is this:
js:
sendInformation(information)
python:
recieveInformation()
sendNewInformation()
js:
recievNewInformation()
You should determine which code is the server and which one is the client. I assume your Python code is your server.
You can run a server in python using:
import socket
HOST = '0.0.0.0'
PORT = 9999
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
And then you can connect your Nodejs client code to the server:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 9999;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('Message from client');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});

Heroku Sockets Javascript

I have the following example using Node.js for the server that sends data via Socket.io to a Javascript file. All works well locally, but when I uploaded to Heroku, it does not. I have tried a lot of tips I found online, but I am always stuck and can't get it through. At the moment, I don't get errors, but I also can't see the values coming through.
Here is the code I use at the moment:
var express = require('express');
var socket = require('socket.io');
//store the express functions to var app
var app = express();
//Create a server on localhost:3000
var server = app.listen(process.env.PORT || 3000);
//var server = app.listen((process.env.PORT || 3000, function(){
//console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
//});
//host content as static on public
app.use(express.static('public'));
console.log("Node is running on port 3000...");
//assign the server to the socket
var io = socket(server);
//dealing with server events / connection
io.sockets.on('connection', newConnection); //callback
//function that serves the new connection
function newConnection(socket){
console.log('New connection: ' + socket.id);
socket.on('incomingDataToServer', emitFunction);
function emitFunction(data){
//setInterval(() => socket.broadcast.emit('ServerToClient', new Date().toTimeString()), 1000);
let randNum;
setInterval(function(){
//get a random value, and assign it a new variable
randNum = getRandomInt(0, 100);
}, 1000);
socket.broadcast.emit('ServerToClient', randNum);
//following line refers to sending data to all
//io.sockets.emit('mouse', data);
console.log(randNum);
}
}
And the Javascript here:
let socket;
socket = io();
socket.on('ServerToClient', socketEvents);
function socketEvents(data){
incomingData = data;
console.log(data);
}
Any help is appreciated.
Thanks
Write app.use before the app listen
and modify app.listen as below and check heroku logs for console message.
app.use(express.static('public'));
var server = app.listen(port, function() {
console.log('Server running on ' + port + '.');
});
if It still not work let me know.

Connect to a third party socket.io server

I'm creating a socket.io server like so:
var http = require('http');
var io = require('socket.io');
var port = 8080;
var server = http.createServer(function(req, res){
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(port);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
console.log('Connection to client established');
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
console.log('Server running at http://127.0.0.1:' + port + '/');
The server works fine and starts, however when I'm connecting through js like this:
$(function(){
var socket = io();
socket.connect('http://localhost:8080');
});
It's not connecting and I'm getting this in dev tools console.
polling-xhr.js:264 GET http://file/socket.io/?EIO=3&transport=polling&t=Lz53lhL net::ERR_NAME_NOT_RESOLVED
I'm loading socket.io.js like this:
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
Change
$(function(){
var socket = io();
socket.connect('http://localhost:8080');
});
to
$(function(){
var socket = io('http://localhost:8080');
});
You need to pass the url of your socket server to the io function

NodeJS simple UDP client server application using broker

I am writing a simple client server NodeJS application using UDP protocol. The main point of this application is that it requires the use of a broker, whose function, in the given case, is to link the sender with the receiver. The requirements tell me that the sender doesn't need to be aware of the receiver's IP address and port number - it only needs to know the broker's corresponding IP and PORT. Afterwards, the broker will send the client's message to the server, based on the server's IP and PORT.
To clarify the previous(?confusing) paragraph, below you will find a illustration of what I've done so far:
sender.js
var PORT1 = XXXXX;
var HOST = '127.0.0.1';
var fs = require('fs');
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
fs.readFile('Path/to/the/file','utf8', function (err, data) {
if (err) throw err;
var message = new Buffer(data);
client.send(data, 0, message.length, PORT1, HOST, function(err, bytes) {
if (err) throw err;
console.log('UDP message sent to ' + HOST +':'+ PORT1);
client.close();
});
});
The code above reads from a file, stores its contents in a buffer and sends it to the broker's port(the broker listens to the same port) and host(which, in my case is the localhost).
broker.js
var PORT1 = XXXXX;
var PORT2 = YYYYY;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
var client = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
console.log('UDP broker listening on ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
client.send(message, 0, message.length, PORT2, HOST, function(err, bytes) {
if (err) throw err;
console.log('UDP message sent to ' + HOST +':'+ PORT2);
client.close();
});
console.log(remote.address + ':' + remote.port +' - ' + message);
});
server.bind(PORT1, HOST);
Here, PORT1 is the port that the broker listens to(waiting for incoming messages from sender) and PORT2 is the port which transmits the message to the receiver(and correspondingly, the receiver listens to this port).
receiver.js
var PORT2 = YYYYY;
var HOST = '127.0.0.1';
var fs = require('fs');
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
var parser = require('xml2json');
server.on('listening', function () {
var address = server.address();
console.log('UDP receiver listening on ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
console.log(remote.address + ':' + remote.port +' - ' + message);
var contents = fs.writeFile("/Path/To/Written/File", parser.toJson(message),
function(error){
if (error) {
console.log("error writing");
}
console.log("File was saved");
});
});
server.bind(PORT2, HOST);
The receiver gets the message from the broker and writes it to a file in the JSON format.
Here are the results:
Sender
UserName's-MacBook-Pro:UDP server UserName$ node sender.js
UDP message sent to 127.0.0.1:XXXXX
Broker
UserName's-MacBook-Pro:UDP server UserName$ node broker.js
UDP broker listening on 127.0.0.1:XXXXX
127.0.0.1:60009 - <?xml version="1.0"?>
<Some XML content here>
</XML content ends here>
UDP message sent to 127.0.0.1:YYYYY
Receiver
UserName's-MacBook-Pro:UDP server UserName$ node receiver.js
UDP receiver listening on 127.0.0.1:YYYYY
127.0.0.1:63407 - <?xml version="1.0"?>
<XML contents here>
</XML content ends here>
File was saved
I am sorry for the long post, but I want to specify all the details to eliminate(hopefully) any ambiguities. Now, to the matter,
HERE is my question
What changes should I make for the broker in order to solve the following problem:
In case of multiple senders and receivers, the broker should manage the ports to link the sender to the receiver(with any specified criteria).
Thank you in advance!
Take a look in this book "Node.js Design Patterns,Publisher:Packt Publishing By: Mario Casciaro ISBN: 978-1-78328-731-4 Year: 2014" at page 361. There is the exact thing you want to do with very good explanation.
Hope it will help!

Cannot connect to secure socket.io server : ERR_SSL_PROTOCOL_ERROR

I'm trying to use socket.io with existing application. My application runs on https://somedomain.com. Its using this code to connect to socket io server:
var socket = io('https://localhost:3456/');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
My socket.io server has this code to listen to incoming connections:
var io = require('socket.io').listen(3456);
io.sockets.on('connection', function(socket) {
console.log("dupa");
socket.on('message', function() {});
socket.on('disconnect', function() {});
});
dupa is never displayed on server side and in Chrome browser console I receive:
GET https://localhost:3456/socket.io/?EIO=3&transport=polling&t=1412901063154-0 net::ERR_SSL_PROTOCOL_ERROR
How can I get this possibly working?
Change https to http
var socket = io.connect("http://localhost:4000");
Your socket server is not using SSL.
First, add the secure parameter to your client (maybe redundant with the https but SSL+socket.io does weird stuff sometimes):
var socket = io.connect('https://localhost', {secure: true});
Then, you need your socket to be secure too :
var privateKey = fs.readFileSync('YOUR SSL KEY').toString();
var certificate = fs.readFileSync('YOUR SSL CRT').toString();
var ca = fs.readFileSync('YOUR SSL CA').toString();
var io = require('socket.io').listen(3456,{key:privateKey,cert:certificate,ca:ca});

Categories