So I have set up a web RTC connection, nearly fully understand the steps and mechanisms involved and have a test out on the web with a full SSL certificate (so I can use it on chrome) but It doesn't ever seem to work with computers that are not under the same wireless connection/router.
In my test I have logged that there are ICE candidates generated and that the two browsers are communicating but I get no video feed except for when the two trying to communicate are under the same connection.
Browser Side to set up webRTC:
var socket = io.connect();
var isChannelReady;
var isInitiator = false;
var isStarted = false;
var localStream;
var pc;
var remoteStream;
var turnReady;
var pc_config = {'iceServers': [{'url': 'stun:stun.l.google.com:19302'}]};
var pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': true}]};
// Set up audio and video regardless of what devices are present.
// var sdpConstraints = {'mandatory': {
// 'OfferToReceiveAudio':true,
// 'OfferToReceiveVideo':true }};
var sdpConstraints = {
optional: [],
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
};
function sendMessage(message){
console.log('Client sending message: ', message);
// if (typeof message === 'object') {
// message = JSON.stringify(message);
// }
socket.emit('message', message);
}
socket.on('message', function (message){
console.log('Client received message:', message);
if (message === 'got user media') {
maybeStart();
} else if (message.type === 'offer') {
if (!isInitiator && !isStarted) {
maybeStart();
}
pc.setRemoteDescription(new RTCSessionDescription(message), function(){doAnswer()});
} else if (message.type === 'answer' && isStarted) {
pc.setRemoteDescription(new RTCSessionDescription(message));
} else if (message.type === 'candidate' && isStarted) {
var candidate = new RTCIceCandidate({
sdpMLineIndex: message.label,
candidate: message.candidate
});
pc.addIceCandidate(candidate);
} else if (message === 'bye' && isStarted) {
handleRemoteHangup();
}
});
////////////////////////////////////////////////////
var localVideo = document.getElementById('localVideo');
var remoteVideo = document.getElementById('remoteVideo');
function handleUserMedia(stream) {
console.log('Adding local stream.');
console.log(localVideo);
localVideo.src = window.URL.createObjectURL(stream);
localStream = stream;
sendMessage('got user media');
if (isInitiator) {
maybeStart();
}
}
function handleUserMediaError(error){
console.log('getUserMedia error: ', error);
}
// window.onload = function () {
// var localVideo = document.getElementById('localVideo');
// var remoteVideo = document.getElementById('mehh');
// }
var constraints = {video: true};
navigator.getUserMedia(constraints, handleUserMedia, handleUserMediaError);
console.log('Getting user media with constraints', constraints);
if (location.hostname != "localhost") {
requestTurn('https://computeengineondemand.appspot.com/turn?username=41784574&key=4080218913');
}
function maybeStart() {
if (!isStarted && typeof localStream != 'undefined' && isChannelReady) {
createPeerConnection();
pc.addStream(localStream);
isStarted = true;
console.log('isInitiator', isInitiator);
if (isInitiator) {
doCall();
}
}
}
window.onbeforeunload = function(e){
sendMessage('bye');
}
/////////////////////////////////////////////////////////
function createPeerConnection() {
try {
pc = new RTCPeerConnection(null);
pc.onicecandidate = handleIceCandidate;
pc.onaddstream = handleRemoteStreamAdded;
pc.onremovestream = handleRemoteStreamRemoved;
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
}
function handleIceCandidate(event) {
console.log('handleIceCandidate event: ', event);
if (event.candidate) {
sendMessage({
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate});
} else {
console.log('End of candidates.');
}
}
function handleRemoteStreamAdded(event) {
console.log('Remote stream added.');
remoteVideo.src = window.URL.createObjectURL(event.stream);
remoteStream = event.stream;
}
function handleCreateOfferError(event){
console.log('createOffer() error: ', e);
}
function doCall() {
console.log('Sending offer to peer');
pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
}
function doAnswer() {
console.log('Sending answer to peer.');
pc.createAnswer(setLocalAndSendMessage, function(err){if(err) throw err;}, sdpConstraints);
}
function setLocalAndSendMessage(sessionDescription) {
// Set Opus as the preferred codec in SDP if Opus is present.
sessionDescription.sdp = preferOpus(sessionDescription.sdp);
pc.setLocalDescription(sessionDescription);
console.log('setLocalAndSendMessage sending message' , sessionDescription);
sendMessage(sessionDescription);
}
function requestTurn(turn_url) {
var turnExists = false;
for (var i in pc_config.iceServers) {
if (pc_config.iceServers[i].url.substr(0, 5) === 'turn:') {
turnExists = true;
turnReady = true;
break;
}
}
if (!turnExists) {
console.log('Getting TURN server from ', turn_url);
// No TURN server. Get one from computeengineondemand.appspot.com:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4 && xhr.status === 200) {
var turnServer = JSON.parse(xhr.responseText);
console.log('Got TURN server: ', turnServer);
pc_config.iceServers.push({
'url': 'turn:' + turnServer.username + '#' + turnServer.turn,
'credential': turnServer.password
});
turnReady = true;
}
};
xhr.open('GET', turn_url, true);
xhr.send();
}
}
function handleRemoteStreamAdded(event) {
console.log('Remote stream added.');
remoteVideo.src = window.URL.createObjectURL(event.stream);
remoteStream = event.stream;
}
function handleRemoteStreamRemoved(event) {
console.log('Remote stream removed. Event: ', event);
}
function hangup() {
console.log('Hanging up.');
stop();
sendMessage('bye');
}
function handleRemoteHangup() {
// console.log('Session terminated.');
// stop();
// isInitiator = false;
}
function stop() {
isStarted = false;
// isAudioMuted = false;
// isVideoMuted = false;
pc.close();
pc = null;
}
///////////////////////////////////////////
// Set Opus as the default audio codec if it's present.
function preferOpus(sdp) {
var sdpLines = sdp.split('\r\n');
var mLineIndex;
// Search for m line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('m=audio') !== -1) {
mLineIndex = i;
break;
}
}
if (mLineIndex === null || mLineIndex === undefined) {
return sdp;
}
// If Opus is available, set it as the default in m line.
for (i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('opus/48000') !== -1) {
var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
if (opusPayload) {
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
}
break;
}
}
// Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
return sdp;
}
function extractSdp(sdpLine, pattern) {
var result = sdpLine.match(pattern);
return result && result.length === 2 ? result[1] : null;
}
// Set the selected codec to the first in m line.
function setDefaultCodec(mLine, payload) {
var elements = mLine.split(' ');
var newLine = [];
var index = 0;
for (var i = 0; i < elements.length; i++) {
if (index === 3) { // Format of media starts from the fourth.
newLine[index++] = payload; // Put target payload to the first.
}
if (elements[i] !== payload) {
newLine[index++] = elements[i];
}
}
return newLine.join(' ');
}
// Strip CN from sdp before CN constraints is ready.
function removeCN(sdpLines, mLineIndex) {
console.log(sdpLines[mLineIndex])
var mLineElements = sdpLines[mLineIndex].split(' ');
// Scan from end for the convenience of removing an item.
for (var i = sdpLines.length-1; i >= 0; i--) {
var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
if (payload) {
var cnPos = mLineElements.indexOf(payload);
if (cnPos !== -1) {
// Remove CN payload from m line.
mLineElements.splice(cnPos, 1);
}
// Remove CN line in sdp
sdpLines.splice(i, 1);
}
}
sdpLines[mLineIndex] = mLineElements.join(' ');
return sdpLines;
}
/////////////////////////////////////////////
room = prompt("Enter room name:");
var socket = io.connect();
if (room !== '') {
console.log('Create or join room', room);
socket.emit('create or join', room);
}
socket.on('created', function (room){
console.log('Created room ' + room);
isInitiator = true;
});
socket.on('full', function (room){
console.log('Room ' + room + ' is full');
});
socket.on('join', function (room){
console.log('Another peer made a request to join room ' + room);
console.log('This peer is the initiator of room ' + room + '!');
isChannelReady = true;
});
socket.on('joined', function (room){
console.log('This peer has joined room ' + room);
isChannelReady = true;
});
socket.on('log', function (array){
console.log.apply(console, array);
});
////////////////////////////////////////////////
And here is everything on the server side pertaining to webRTC (using socket io):
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket){
console.log('connected');
// convenience function to log server messages on the client
function log(){
var array = [">>> Message from server: "];
for (var i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
socket.on('message', function (message) {
log('Got message:', message);
// for a real app, would be room only (not broadcast)
socket.broadcast.emit('message', message);
});
socket.on('create or join', function (room) {
//io.sockets.clients(room)
//io.of('/').in(room).clients
//io.sockets.adapter.rooms[room]
var numClients;
var ish = io.sockets.adapter.rooms[room];
(ish === undefined) ? numClients = 0 : numClients = ish.length
log('Room ' + room + ' has ' + numClients + ' client(s)');
log('Request to create or join room ' + room);
if (numClients === 0){
socket.join(room);
socket.emit('created', room);
} else if (numClients === 1) {
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room);
} else { // max two clients
socket.emit('full', room);
}
socket.emit('emit(): client ' + socket.id + ' joined room ' + room);
socket.broadcast.emit('broadcast(): client ' + socket.id + ' joined room ' + room);
});
});
I simply can't find any errors that prevent the streams from being sent...
More than willing to do a private chat so I can get moving on my project.
Related
I'm using socket.io v4 with NodeJS (Express).
So, the situation that I have is that I have a chat window for client and the client can enter their email and message. Now, I want to create a room based on that email and have another client join that room. My current implementation doesn't work. It creates the room but the other client is unable to join it.
Server Side Code:
io.of(/^\/dynamic-[a-zA-Z0-9]+$/).on("connection", (socket) => {
let email;
const namespace = socket.nsp.name;
let namespaceToCheck = namespace.split('-');
//console.log(namespaceToCheck[1])
User.findOne({apiKey: namespaceToCheck[1]})
.then((doc)=> {
if(namespaceToCheck[1] == doc.apiKey) {
socket.once("pass-email", (data) => {
io.of(namespace).emit("pass-email", data);
email = data;
})
console.log("Valid Connection");
socket.on("chat-message", (msg) => {
socket.join(email, function(){
//console.log(`Socket now in ${socket.rooms}`);
});
//console.log(msg);
console.log(socket.rooms);
Message.findOne({namespace: namespace})
.then((doc) => {
// console.log(doc);
doc.messages.push(msg);
doc.save().then((saved) => { return Promise.resolve(saved) });
})
// console.log(socket.handshake);
//io.of(namespace).sockets.in(data).emit("chat-message", msg);
console.log(email);
io.of(namespace).to(email).emit("chat-message", msg);
})
}
})
.catch((err)=> {
console.log(err);
})
});
Client Socket Code (from which I'm passing the email)
var chatSocket = io("http://localhost:3000/dynamic-8171d2a713d65c5edf81e45af4d14558a2c62275df05c73ca198a94d422e5948");
var chatBtn = document.querySelector('.chat-btn');
var input = document.querySelector('.chat-input');
var messages = document.querySelector(".messages");
var emailInputTag = document.querySelector(".email-input");
input.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
if (input.value && emailInputTag.value) {
chatSocket.emit('create-room', emailInputTag.value);
//chatSocket.join(emailInputTag.value)
chatSocket.emit('chat-message', emailInputTag.value + ':' + input.value);
input.value = '';
}
}
});
chatBtn.addEventListener('click', function(e) {
e.preventDefault();
if (input.value && emailInputTag.value) {
chatSocket.emit('chat-message', emailInputTag.value + ':' + input.value);
input.value = '';
}
});
chatSocket.on('chat-message', function(msg) {
var item = document.createElement('div');
item.classList.add('msg');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
This is the rooms that this socket is in:
Client chat socket code (from which I want to receive room event and join the received room)
var chatSocket = io(`http://localhost:3000/dynamic-${ApiKey}`);
chatSocket.on("connect", function () {
console.log("Connected-test-succeeded");
// Connected, let's sign-up for to receive messages for this room
});
chatSocket.on("pass-email", (val) => {
console.log(val);
console.log("Listening");
});
var chatBtn = document.querySelector(".chat-btn");
var input = document.querySelector(".chat-input");
var messages = document.querySelector(".messages");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
if (input.value) {
chatSocket.emit();
chatSocket.emit(
"chat-message",
"Owner" + ":" + input.value
);
input.value = "";
}
}
});
chatBtn.addEventListener("click", function (e) {
e.preventDefault();
if (input.value) {
chatSocket.emit(
"chat-message",
"Owner" + ":" + input.value
);
input.value = "";
}
});
chatSocket.on("chat-message", function (msg) {
console.log("Message received: " + msg);
var item = document.createElement("div");
item.classList.add("msg");
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
P.S: I know that the code is a bit messy but what I'm trying to do here is making a tawk.to clone so different namespace for each website url and the rooms are different in the said namespace for different users.
I am new to nodejs so below is my code, I need to add try-catch blocks for my below code need some help to do this because new to this things, below is my websocket code newly created I need to add try-catch blocks for this , please help me out anyone
var WebSocket = require('ws');
//var Stomp = require('stompjs');
function CustomWebSocketListener(config) {
RED.nodes.createNode(this,config);
var node = this;
node.on('input', function(msg) {
let temp =msg.payload;
let urllist = temp.url;
let urls=[]
if(global.websocket!=null || global.websocket!=undefined){
let connections=global.websocket;
console.log("global")
if(global.isAccessTokenExpired){
for(let k in connections) {
connections[k].close();
connections[k].reconnect=false
console.log('connection closed:::');
}
urls=urllist;
}
else{
for(let i=0;i<urllist.length;i++){
let group=urllist[i].split("/")[7].split("?");
if(!connections[group[0]]){
urls.push(urllist[i])
}
}
}
}
else{
urls=urllist;
}
console.log("urls.length::::"+urls.length)
if(urls.length > 0){
for(let i=0;i<urls.length;i++){
console.log(':::::::for loop:::::::')
console.log('url----'+urls[i])
function connect(urlIndex) {
let ws;
if(urlIndex!=undefined||urlIndex!=null){
ws = new WebSocket(urls[urlIndex]);
}
else{
ws = new WebSocket(urls[i]);
}
ws.index=i;
ws.reconnect=true;
ws.onopen = function() {
};
ws.onmessage = function(e) {
console.log('Message:', e.data);
console.log('Socket is closed. Reconnect will be attempted in 30 second.', e.reason);
setTimeout(function() {
console.log("onclose ----ws reconnect"+ws.reconnect)
if(ws.reconnect){
console.log("inside if reconnect")
connect(ws.index);
}
}, 30000);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
if(global.websocket==null || global.websocket==undefined){
global.websocket={};
console.log(global.websocket)
global.websocket[urls[i]]=ws;
}
else{
global.websocket[urls[i]]=ws;
}
}
connect();
}
}
});
}
RED.nodes.registerType("custom-websocketlistener",CustomWebSocketListener);
}
Thanks for anyone who would help me out with this
you can directly use where you want like this...
try{
//whatever you want
}
catch(e){
//whatever you want
}
In your code you can use like this
try {
RED.nodes.createNode(this, config)
var node = this
node.on('input', function(msg) {
let temp = msg.payload
let urllist = temp.url
let urls = []
if (global.websocket != null || global.websocket != undefined) {
let connections = global.websocket
console.log('global')
if (global.isAccessTokenExpired) {
for (let k in connections) {
connections[k].close()
connections[k].reconnect = false
console.log('connection closed:::')
}
urls = urllist
} else {
for (let i = 0; i < urllist.length; i++) {
let group = urllist[i].split('/')[7].split('?')
if (!connections[group[0]]) {
urls.push(urllist[i])
}
}
}
} else {
urls = urllist
}
console.log('urls.length::::' + urls.length)
if (urls.length > 0) {
for (let i = 0; i < urls.length; i++) {
console.log(':::::::for loop:::::::')
console.log('url----' + urls[i])
function connect(urlIndex) {
let ws
if (urlIndex != undefined || urlIndex != null) {
ws = new WebSocket(urls[urlIndex])
} else {
ws = new WebSocket(urls[i])
}
ws.index = i
ws.reconnect = true
ws.onopen = function() {}
ws.onmessage = function(e) {
console.log('Message:', e.data)
console.log('Socket is closed. Reconnect will be attempted in 30 second.', e.reason)
setTimeout(function() {
console.log('onclose ----ws reconnect' + ws.reconnect)
if (ws.reconnect) {
console.log('inside if reconnect')
connect(ws.index)
}
}, 30000)
}
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket')
ws.close()
}
if (global.websocket == null || global.websocket == undefined) {
global.websocket = {}
console.log(global.websocket)
global.websocket[urls[i]] = ws
} else {
global.websocket[urls[i]] = ws
}
}
connect()
}
}
})
} catch (e) {
console.log(e)
}
}
I am writing my first apps with wit.ai using a node.js backend. I found some posts here similar to my question, but not really the answer :
I use a socket.io to communicate with my node script.
The two relevant parts of my node are :
io.sockets.on('connection', function (socket) {
socket.on('message',
function(data) {
var json = JSON.parse(data);
var sid = json['sessionid'];
console.log("Received on sid " + sid);
if (_sessions[sid] == undefined) {
_sessions[sid] = {};
_sessions[sid].context = {};
}
_sessions[sid].socket = socket;
client.runActions(sid, json['text'], _sessions[sid].context, 30)
.then((context) => {
_sessions[sid].context = context;
}
)
.catch((err) =>
{
console.error('Oops! Got an error from Wit: ', err.stack || err);
}
);
}
);
}
);
========
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
return new Promise(function(resolve, reject) {
var session = _sessions[sessionId];
console.log("-------------------------------");
console.dir(context);
console.log("-------------------------------");
session.socket.emit("message", JSON.stringify(response));
return resolve();
});
},
gettaxi ({sessionid, context, text, entities}) {
return new Promise(function(resolve, reject) {
console.log(`Session ${sessionid} received ${text}`);
var quand = firstEntityValue(entities, "quand");
if (!quand && context['quand'] != undefined) quand = context['quand'];
var depart = firstEntityValue(entities, "depart");
var arrivee = firstEntityValue(entities, "arrivee");
if (depart) {
console.log("Found depart");
context.depart = depart;
delete context.missing_depart;
}
else {
context.missing_depart = true;
}
if (arrivee) {
console.log("Found arrivee");
context.arrivee = arrivee;
delete context.missing_arrivee;
}
else {
context.missing_arrivee = true;
}
console.dir(context);
if (quand) {
console.log("Found quand");
context.quand = quand;
delete context.missing_quand;
}
else {
context.missing_quand = true;
}
return resolve(context);
}
);
},
};
All is working rather good, except than my gettaxi receives a undefined sessionid.
It's not the case for the send function that receives the correct sessionid.
What am I doing wrong ?
I would like to transfer files between one client, and a server.
I only use stream, and fs modules.
For the moment, I can transfer ".txt" files perfectly, but it does not work for ".mp3" files (for instance). Indeed, the size of the ".mp3" file saved from the server has a bigger size than the original file. (eg : 9,2 mo instead of 5mo) and I can not open it.
Here is my server part:
var net = require('net');
var util = require("util");
var fs = require('fs');
var receive_object = {};
var server = net.createServer(function (socket){
console.log('server connected');
socket.write('hello\r\n');
//socket.pipe(socket);
socket.on('data',function(data){
if(data.toString() == "upload_demand"){
socket.write("upload_demand_ok");
}else if(data.toString().indexOf("fileName")>-1){
data = data.toString().replace("fileName","");
fs.exists("server_"+data, function(exists){
if(exists) socket.write("fileName_ko");
else{
receive_object.fileName = data;
receive_object.writable = fs.createWriteStream("server_"+receive_object.fileName);
receive_object.contenu = "";
socket.write("fileName_ok");
}
});
}else if(data.toString().indexOf("size")>-1){
data = data.toString().replace("size","");
receive_object.size_total = data;
receive_object.size_received = 0;
socket.write("size_ok");
}/*else if(data.toString()=="upload_success"){
receive_object.writable.write(receive_object.contenu);
console.log('It\'s saved!');
}*/
else{
receive_object.size_received += 64*1024;
socket.write("uploading"+parseInt(receive_object.size_received/receive_object.size_total*100));
receive_object.contenu += data;
}
});
socket.on('end', function() {
console.log('client disconnected');
receive_object.writable.write(receive_object.contenu);
});//socket on
});
/**
let's listening the server
*/
server.listen(1337, '127.0.0.1',function(){
console.log("server bound on port %j and on address %j",server.address().port,server.address().address);
});
Here is my client part:
var util = require("util");
var net = require("net");
var fs = require('fs');
var fileName = "exemple.txt";
/**
client connecting to the corresponding port Server
*/
var client = net.connect({port: 1337}, function () {
util.log("Client connected");
fs.exists(fileName, function(exists) {
if (exists) {
fs.stat(fileName, function(error, stats) {
transfer_object = {};
transfer_object.fileName = fileName;
transfer_object.size = stats.size;
transfer_object.stream = fs.createReadStream(fileName, { bufferSize: 64 * 1024 });
transfer_object.progression = 0;
client.write("upload_demand");
});
}else{
console.log("fileNotFound");
}
});
});
client.on('data', function(data) {
if(data=="upload_demand_ok"){
console.log(''+data);
client.write("fileName"+transfer_object.fileName);
}
else if(data == "fileName_ok"){
console.log(''+data);
client.write("size"+transfer_object.size)
}else if(data == "fileName_ko"){
console.log('ficher deja existant');
}else if(data == "size_ok"){
console.log(''+data);
transfer_object.stream.pipe(client,{ end: true });
}else if(data.toString().indexOf("uploading")>-1){
data = parseInt(data.toString().replace("uploading",""));
progressbar(data);
//if(data>=100) client.write('upload_success');
}
});
/**
client receive end event from server
*/
client.on('end', function() {
console.log('client disconnected');
});
function progressbar(int){
if(int>=0 && int<=20 && transfer_object.progression == 0){
transfer_object.progression = 1;
process.stdout.write("progression : [=");
}
else if(int>20 && int<=40 && transfer_object.progression == 1){
transfer_object.progression = 2;
process.stdout.write("==");
}else if(int>40 && int<=60 && transfer_object.progression == 2){
transfer_object.progression = 3;
process.stdout.write("==");
}else if(int>60 && int<=80 && transfer_object.progression == 3){
transfer_object.progression = 4;
process.stdout.write("==");
}else if(int>80 && int<=100 && transfer_object.progression == 4){
transfer_object.progression = 5;
process.stdout.write("=]");
}
}
The txt file has utf8 encoding, and the mp3 - binary encoding.
You can set the encoding usable for stream as described here http://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback
According to http://nodejs.org/api/buffer.html#buffer_buffer
The utf8 is for txt, and binary for mp3 data (but manual do not recommend using it)
here is my current code
'use strict';
var _ = require('underscore'),
util = require('util'),
events = require('events'),
net = require('net'),
colors = require('colors');
// Chatango Socket connection handler, for both Rooms and PM
// Available events: onconnect, data, error, timeout, close, write ( Note: exceptions must be handled! )
function Socket(host, port)
{
this._host = host;
this._port = port || 443;
this._socket = new net.Socket();
this._pingTask = false;
this._connected = false;
this._firstCommand = true;
this._writeLock = false;
this._writeBuffer = [];
this._buffer = '';
this.connect();
}
util.inherits(Socket, events.EventEmitter);
Socket.prototype.connect = function()
{
if(this._socket._connecting) return;
var self = this;
if(this._socket.destroyed){
var reconnecting = true;
console.log('[SOCKET] reconnecting to '+this._host+':'+this._port);
}else{
var reconnecting = false;
console.log('[SOCKET] connecting to '+this._host+':'+this._port);
}
this._writeLock = true;
if(this._socket._events.connect){
this._socket.connect(this._port, this._host);
}else{
this._socket.connect(this._port, this._host, function() {
self._connected = true;
self._writeLock = false;
self._pingTask = setInterval(function() {
if(self._connected) {
self.write(['']);
}
}, 30000);
self.emit('onconnect');
});
}
if(reconnecting) return;
this._socket.on('data', function(data) {
var buffer = data.toString('utf8');
if(buffer.substr(-1) !== '\x00')
{
self._buffer += buffer;
}
else
{
if(self._buffer != '')
{
buffer = self._buffer + buffer;
self._buffer = '';
}
var messages = buffer.split('\x00');
_.each(messages, function(message){
message = message.replace(/(\r|\n)/g, '');
if(message !== '')
self.emit('data', message);
});
}
});
this._socket.on('error', function(exception) {
self.emit('error', exception);
});
this._socket.on('timeout', function(exception) {
self.emit('timeout', exception);
});
this._socket.on('close', function() {
self._connected = false;
self._writeBuffer = [];
self._writeLock = false;
self._buffer = '';
self._firstCommand = true;
clearInterval(self._pingTask);
self.emit('close');
});
}
Socket.prototype.disconnect = function(){
this._socket.destroy();
}
Socket.prototype.setWriteLock = function(bool) {
this._writeLock = _.isBoolean(bool) && bool;
}
Socket.prototype.write = function(data) {
if(this._connected)
{
if(this._firstCommand)
{
var terminator = '\x00';
this._firstCommand = false;
}
else
var terminator = '\r\n\x00';
if(this._writeLock)
this._writeBuffer.push(data);
else
{
_.each(this._writeBuffer, function(value){
this.write(value);
}.bind(this));
if(data)
this.emit('write', data.join(':'));
this._socket.write(data.join(':') + terminator);
}
}
}
exports.Instance = Socket;
as you can see i am using the net module
i want to change to the ws module and do this using websockets https://github.com/einaros/ws
i've read all kinds of examples but none of them give me what i want
the lib im using is
https://github.com/MakuraYami/derplib