A open source RTMP streaming server for stream mp3 on deman? - streaming

I need a open source RTMP server for stream mp3s on demand for linux(centos), i found a few but these dont let me stream on demand, just only live. thanks

this does on demand ... just install node.js and execute using :
node file_containing_below.js
and yes consider it open source ;-)
var http = require('http');
var fs = require('fs');
var util = require('util');
var port = 8888;
var host = "localhost";
http.createServer(function (req, res) {
var path = "/path/to/some/video/or/audio/file.mp3"; // mp4 or most any video/audio file
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers.range) { // meaning client (browser) has moved the forward/back slider
// which has sent this request back to this server logic ... cool
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1;
var chunksize = (end-start)+1;
console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
file.pipe(res);
} else {
console.log('ALL: ' + total);
res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'video/mp4' });
fs.createReadStream(path).pipe(res);
}
}).listen(port, host);
console.log("Server running at http://" + host + ":" + port + "/");
now just point some client (your browser) at URL
http://localhost:8888/
and yes once playing the forward/back sliders automagically work on an arbitrary client (browser)

Related

Node Js TCP Client not receiving data in a loop

I need continuous data receiving. but i tried with out setinterval() but no success. Then i tried setinterval() also no success i am receiving first response after sending message no success can you please help me.
this is the output;[enter image description here][1]
var HOST = '202.71.103.XXX';
var PORT = XXXX;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('init');
setInterval(getData, 1000);
});
function getData() {
console.log('fun called')
client.on('data', function(data) {
console.log('Get Data: ' + data)
Cdata = JSON.parse(data.slice(0, -2))
if (Cdata.ServerDist == 1) {
var sentMsg = '{"ClientID":"' + Cdata.ClientID + '","TrackSystemNos":"13992881XXX|"}';
client.write(sentMsg)
console.log('Sent Msg: ' + sentMsg)
}
});
}
[1]: https://i.stack.imgur.com/7Mt0Y.png
Okay so I am not 100% sure what your specific issue is but I wrote a simple client and server based on your code and it works pretty well so see if that helps you.
Server:
const net = require('net');
var dummy = {
ServerDist: 1
};
var server = net.createServer(function(socket) {
let temp = JSON.stringify(dummy)
console.log(temp);
socket.write(temp);
socket.on('data', data => {
let temp = JSON.stringify(dummy);
console.log(temp);
socket.write(temp);
});
});
server.listen(1337, '127.0.0.1');
Client
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 1337;
var client = new net.Socket();
client.connect(PORT, HOST, function () {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('init');
});
client.on('data', function (data) {
console.log('Get Data: ' + data);
let Cdata = JSON.parse(data);
if (Cdata.ServerDist === 1) {
let sentMsg = {ClientID: 'Bob', TrackSystemNos: '13992881XXX'};
client.write(JSON.stringify(sentMsg));
console.log('Sent Msg: ' + JSON.stringify(sentMsg))
}
}
);
Output:
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Old Answer
I believe your problem is setinterval is a asynchronous call. So as soon as you call it the code continues out of the connect function (most likely ending the connection). The setinterval gets the first response because it is there from the call before the close but since the connection is closed it doesn't get any more.
Have you tried using a while loop inside the connect to keep the connection open?

Flutter: how to create post request with form data same js code

I want to upload an image to the server with flutter, in js t use form data with input file but with flutter I don't know what to do.
in js:
formData.append("file", e.clipboardData.files[0]);
formData.append("session", sessionid);
formData.append("fileindex", fileListIndex);
var hostname = window.location.hostname;
var protocol = window.location.protocol;
if (hostname === "localhost") {
xhr.open("POST", "http://localhost:9999/" + uploadpoint, true);
} else if (hostname === "www.aladin.finance") {
xhr.open("POST", protocol + "//uploadfile.aladin.finance" + "/"
+ uploadpoint, true);
} else {
xhr.open("POST", protocol + "//uploadfile." + hostname + "/"
+ uploadpoint, true);
}
xhr.withCredentials = true;
xhr.send(formData);
Flutter has this great package called Dio to handle all sort of http requests. It's very easy to do what you want with it. Check this: https://pub.dev/packages/dio#sending-formdata

Nodejs - websocket-node module: How to make multi-client socket-server works?

I created a socket server using websocket module with this configuration taken from this example (with some changes):
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
I create my own client in html :
<html>
<head>
<script src='./js/jquery1-11-3-min.js'></script>
<script>
$(document).ready(function (){
buildwebsocket();
});
var ws;
function buildwebsocket(){
ws = new WebSocket("ws://192.168.0.96:5050",'echo-protocol');
ws.onopen = function(evt) { onOpen(evt) };
ws.onclose = function(evt) { onClose(evt) };
ws.onmessage = function(evt) { onMessage(evt) };
ws.onerror = function(evt) { onError(evt) };
}
function onOpen(ev){
//alert("konek men! mantap! :D");
$("#recmsg").append("connected!<br>");
}
function onClose(ev){
$("#recmsg").append("connection closed!<br>");
}
function onMessage(ev){
//alert("ada pesan datang!");
$("#recmsg").append(ev.data+"<br>");
}
function onError(ev){
$("#recmsg").append("connecting error!<br>");
}
function doSend(){
//writeToScreen("SENT: " + message);
var message = $("#pesan").val();
ws.send(message);
} function doClose(){
ws.close();
}
//function writeToScreen(message){
//var pre = document.createElement("p");
//pre.style.wordWrap = "break-word";
//pre.innerHTML = message;
//output.appendChild(pre);
//}
//window.addEventListener("load", init, false);
</script>
</head>
<body>
<button onclick='doClose()'>Close</button>
<textarea id='pesan'></textarea><br>
<button onclick='doSend()'>Kirim!</button>
<br>
received message
<div id='recmsg'>
</div>
</body>
</html>
The connection between client (first client) and the server was successfully established. I try to send messages from first client, then the server receives the message without any promblem, and then the message sent back to the first client, and the first client receives it. I can say the connection and the socket works well.
I try to establish another connection (second client), so I open the second client in another device. The connection is good. But, when I send messages from the first or the second client, the first client doesn't get the response but the second client gets it.
And if open the third client and then send a message, the first and the second client don't get the response. Only the last connected client receives the response from server, and there's no client receives any error messages.
Is it the cons of the module? or the server configuration must be changed/added?
Can I establish multi-client-supported-socket-server using this module?
You're not storing the connections on the server side. You're just setting them up on the server to communicate directly back and forth to the server. If you want messages going to the server to be sent back out to everyone, you need to set up the .on('message', ...) function for each connection on the server to have that behavior. To do this, you'll need to store the connections as they are created. Try this:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
//create an array to hold your connections
var connections = [];
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
//store the new connection in your array of connections
connections.push(connection);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//send the received message to all of the
//connections in the connection array
for(var i = 0; i < connections.length; i++) {
connections[i].sendUTF(message.utf8Data);
}
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});

NodeJS basic POST request - Socket hung up

I am currently playing around with NodeJS and I have created a GET request fine, no issues with that, as soon as I try and post something to a form, I get 'socket hung up' error.
Here is my code:
var http = require('http');
var mathResult = 123;
var options = {
host: 'directus.darkscience.net',
path: '/',
port: '6789',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-urlencoded'
}
};
var post_req = http.request(options, function(res){
console.log('HERE');
res.setEncoding('utf8');
res.on('data', function(chunk){
console.log('CHUNK');
var result = chunk.match(/correct/i);
if(result.length > 0){
console.log(result);
}
});
});
post_req.on('error', function(e){
console.log('Post Error : ' + e.message);
});
post_req.end('amount='+mathResult);
I have no idea what I'm doing wrong.
Could anyone please point me in the right direction?

creating a tcp socket with net.createConnection(port, [host]) in node.js

Anyone here can give me a few pointers working with sockets in node.js?
can open a tcp connection say on 172.0.0.1 on port 8000 for example using net.createConnection(port, host)
var net = require('net'),
querystring = require('querystring'),
http = require('http'),
port = 8383,
host = 172.123.321.213,
path = /path/toService,
_post = '';
var server = http.createServer(function(req, res) {
if(req.method == 'POST') {
req.on('data', function(data) {
body+=data;
});
req.on('end', function() {
_post = querystring.parse(body);//parser post data
console.log(_post);
})
}
var socket = net.createConnection(port, host);
var socket = net.createConnection(port, host);
socket.on('error', function(error) {
send404(res, host, port);
})
socket.on('connect', function(connect) {
console.log('connection established');
res.writeHead(200, {'content-type' : 'text/html'});
res.write('<h3>200 OK:
Connection to host ' + host + ' established. Pid = ' + process.pid + '</h3>\n');
res.end();
var body = '';
socket._writeQueue.push(_post);
socket.write(_post);
console.log(socket);
socket.on('end', function() {
console.log('socket closing...')
})
})
socket.setKeepAlive(enable=true, 1000);
}).listen(8000);
send404 = function(res, host, port) {
res.writeHead(404, {'content-type': 'text/html'});
res.write('<h3>404 Can not establish connection to host: ' + host + ' on port: ' + port + '</h3>\n');
res.end();
}
But now I need to send my data to the path defined - if I add the path to host then try connection then connection will fail.
Any ideas?
Thanks in advance
Your "socket" object is just a plain TCP socket which is just a simple bidirectional communication channel. The HTTP methods you're trying to use (e.g. res.writeHead()) don't pertain, so you'll have to write the request manually. Try something like this:
var socket = net.createConnection(port, host);
console.log('Socket created.');
socket.on('data', function(data) {
// Log the response from the HTTP server.
console.log('RESPONSE: ' + data);
}).on('connect', function() {
// Manually write an HTTP request.
socket.write("GET / HTTP/1.0\r\n\r\n");
}).on('end', function() {
console.log('DONE');
});