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)
Related
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.
For a school project we had to develop a file server and also a chat server. I did both in Node.js. Now I have to merge them, but they're both supposed to listen on the same port.
I have two file which both work. The chat server uses
net.createServer(function (socket){
...
}}).listen(9020);
And the file server uses
http.createServer(function (request, response){
...
}}).listen(9020);
Simple putting all the code in the same file returns an error since you can't have two servers listening on the same port. What's the best way to merge them? Can all the code be run in either the Net or HTTP server? I've tried this but it isn't working for me.
Here's the full code:
chat.js
// Load the TCP Library
net = require('net');
// Keep track of the chat clients
var clients = [];
var chat = [];
// Start a TCP Server
net.createServer(function (socket) {
socket.setEncoding('utf8');
// Identify this client
socket.name = "unknown"
// Put this new client in the list
clients.push(socket);
// Send a nice welcome message and announce
socket.write("Welcome to Michael's chat room" + "\r\n");
//broadcast(socket.name + " joined the chat\r\n", socket);
// Handle incoming messages from clients.
socket.on('data', function (data) {
var textdata = data.toString();
if(textdata.trim() === "adios"){
broadcast("closing connection", socket);
socket.end();
}
else if (textdata.trim() === "help"){
broadcast("*******************Available commands:*******************\r\nhelp Display the program options\r\ntest: <words> Send a test message of <words> that does not get logged\r\nname: <chatname> Set name to <chatname>\r\nget Get the entire chat log\r\npush: <stuff> Add <stuff> to the chat log\r\ngetrange <startline> <endline> Get contents of the chat log from <startline> to <endline>\r\nadios Close connection");
}
else if (startsWith(textdata, "name:")){
var rmv = "name: ";
textdata = textdata.slice( textdata.indexOf( rmv ) + rmv.length );
socket.name = textdata.trim();
broadcast("OK\r\n", socket);
}
else if (startsWith(textdata, "push:")){
var rmv = "push: ";
textdata = textdata.slice( textdata.indexOf( rmv ) + rmv.length );
textdata = textdata.trim();
chat.push(socket.name + ": " + textdata + "\r\n");
broadcast("OK\r\n");
}
else if (startsWith(textdata, "test:")){ //Why do we even have this lever?
var rmv = "test: ";
textdata = textdata.slice( textdata.indexOf( rmv ) + rmv.length );
broadcast(textdata.trim() + "\r\n");
}
else if (textdata.trim() === "get"){
for (var i = 0; i < chat.length; ++i) {
//if (i < 1){
// broadcast(chat[i].toString(), socket);
//}
//else{
broadcast(chat[i].toString(), socket);
//}
}
}
else if (startsWith(textdata, "getrange")){
var rmv = "getrange ";
textdata = textdata.slice( textdata.indexOf( rmv ) + rmv.length );
var newtextdata = textdata;
newtextdata = newtextdata.split(" ");
var stringArray = new Array();
for(var i =0; i < newtextdata.length; i++){
stringArray.push(newtextdata[i]);
if(i != newtextdata.length-1){
//stringArray.push(" ");
}
}
for (var i = stringArray[0]; i <= stringArray[1]; ++i) {
broadcast(chat[i].toString() + "\r\n", socket);
}
}
else{
broadcast("Error: unrecognized command: " + textdata + "\r\n", socket);
}
});
// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left the chat.\r\n");
});
// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function (client) {
// Don't want to send it to sender
///if (client === sender) return; //actually want to send a lot of stuff only to sender - how to do this?
client.write(message);
});
// Log it to the server output too
process.stdout.write(message)
}
function startsWith(str, word) {
return str.lastIndexOf(word, 0) === 0;
}
socket.on('Error', function(err){
console.log("well heck, there's been an error")
});
}).listen(9020);
// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 9020\r\n");
file.js
//based heavily off of https://developer.mozilla.org/en-US/docs/Node_server_without_framework
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request ', request.url);
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
if (filePath == './CHAT')
filePath = './chatform.html';
var extname = String(path.extname(filePath)).toLowerCase();
var contentType = 'text/html';
var mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
};
contentType = mimeTypes[extname] || 'application/octect-stream';
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(9020);
console.log('Server running on port 9020');
I was given a task to send JSON string from client to server and from server to client, whenever there is a new record found to send.
I decided to build TCP connection(suggest me if there is any other better way in Node.js) between server and client to transfer data.
The problem is, I was supposed to use a delimiter to separate JSON strings one from another. I am afraid what if the json string contains the delimiter string inside the object. I am looking for a better way to separate two JSON strings.
Below is my code. Please help me.
Client
var net = require('net')
, client = new net.Socket();
var chunk = ''
, dlim_index = -1
, delimit = '~~';
client.connect(config.Port, config.IpAddress, function () {
console.log('Server Connected');
client.write('CLIENTID:' + process.argv[2]);
client.write(delimit);
});
client.on('data', function (data) {
var recvData = data.toString().trim();
chunk += recvData;
dlim_index = chunk.indexOf(recvData);
console.log(data);
while (dlim_index > -1) {
var useData = chunk.substring(0, dlim_index);
if (useData == 'SUCCESS') {
controller.listenOutQueue(function (dataToSend) {
var object = JSON.parse(dataToSend);
client.write(dataToSend);
client.write(delimit);
});
}
else {
var record = JSON.parse(useData);
controller.insertIntoQueue(record, function (status) {
});
}
chunk = chunk.substring(dlim_index + 2);
dlim_index = chunk.indexOf(delimit);
}
});
client.on('close', function () {
console.log('Connection closed');
});
client.setTimeout(50000, function () {
//client.destroy();
});
Server
var net = require('net')
, server = net.createServer()
, delimit = '~~'
, clients = [];
controller.listenOutQueue(function (dataToSend) {
client.write(dataToSend);
client.write(delimit);
});
server.on('connection', function (socket) {
var chunk = '';
var dlim_index = -1;
socket.on('data', function (data) {
var recvData = data.toString().trim();
chunk += recvData;
dlim_index = chunk.indexOf(delimit);
while (dlim_index > -1) {
var useData = chunk.substring(0, dlim_index);
if (useData.substring(0, 9) == 'CLIENTID:') {
socket.clientid = useData.replace('CLIENTID:', '');
console.log('Client Id: ' + socket.clientid);
clients.push(socket);
var successMessage = "SUCCESS";
socket.write(successMessage);
socket.write(delimit);
}
else {
controller.insertIntoQueue(JSON.parse(useData), function (status) {
});
}
chunk = chunk.substring(dlim_index + 2);
dlim_index = chunk.indexOf(delimit);
}
});
socket.on('end', function () {
console.log('Connection Closed (' + socket.clientid + ')');
});
socket.on('error', function (err) {
console.log('SOCKET ERROR:', err);
});
});
server.listen(config.Port, config.IpAddress);
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
I am trying to make a server and client program just on localhost to be able to upload and list files from the server. I have the code to upload files to the server but for some reason after the server writes the file from the client it has less bytes than the original file.
Here is the client code:
var net = require('net');
var fs = require('fs');
var port='3000';
var host='localhost';
var path=__dirname;
var fileUploadDir = __dirname+'/uploadfolder/';
process.stdin.resume();
var socket = net.connect(port,host);
var stdin = process.stdin;
var stdout = process.stdout;
stdout.on('data', function(d){
console.log("d: "+d);
});
socket.on('connect',function(){
console.log("connected to server");
//stdin.pipe(stdout);
stdin.pipe(socket, {end: false});
});
socket.on('data', function(data){
var b = new Buffer(data, "utf8");
var bStr = b.toString();
if(bStr=="okupload"){
console.log("uploading file");
folderFilesUpload(socket);
}else{
console.log(bStr);
}
});
socket.on('end', function(){
socket = net.connect(port,host);
console.log('socket ended');
});
function folderFilesUpload(socket){
fs.readdir(fileUploadDir, function(err, results){
if(err)
console.log("upload to upload files");
else{
if(results.length > 0){
for(var r in results){
var fullPath = fileUploadDir+results[r];
var fileStream = fs.createReadStream(fullPath);
fileStream.on('open', function(){
fileStream.pipe(socket);
});
}
}else{
console.log("no files to upload");
}
}
});
}
Server Code:
var net=require('net');
var fs=require('fs');
var host ='localhost';
var port='3000';
var outputDir = __dirname+'/outputdir/';
var uploadState = false;
var server = net.createServer(function(conn){
console.log('server connected');
conn.on('data', function(data) {
if(data == "l\n" && !uploadState){
listFiles(conn);
}
if(data == "u\n"){
console.log("switching to upload file state");
uploadState=true;
conn.write("okupload");
}
if(uploadState){
console.log("data");
//console.log("data: "+data);
var file = fs.createWriteStream(outputDir+'temp');
conn.pipe(file);
}
});
conn.on('end', function(){
uploadState = false;
console.log('data has ended');
});
});
server.listen(port,host, function(){
server.on('connection', function(){
console.log('connection made');
});
});
function listFiles(conn){
console.log("listing files");
fs.readdir(outputDir, function(err, results){
if(err){
var b = new Buffer("error listing files", "utf8");
conn.write(b);
}else{
var output = "files: \n";
if(results !== null && results.length >0){
for(var r in results){
output += results[r]+"\n";
}
}else{
output += "no files.\n";
}
var b = new Buffer(output, "utf8");
conn.write(b);
}
});
}