user1261284 user1261284 - 3 months ago 10
Node.js Question

Node js TLS Duplex Stream

i have the following (simplified) code from a recent ruby project for a readable and writeable stream:

class StreamReader
require 'socket'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
def initialize
tcp_client = TCPSocket.new ENV['URL'], ENV['PORT']
context = OpenSSL::SSL::SSLContext.new
context.ssl_version = :TLSv1_2
context.verify_mode = OpenSSL::SSL::VERIFY_PEER
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
context.cert_store = cert_store
@stream_client = OpenSSL::SSL::SSLSocket.new tcp_client, context
@stream_client.connect
@requester = StreamRequester.new
end

def open_stream
login = @requester.create_login_request
@stream_client.puts login
loop do
line = @live_client.gets
puts line.strip if !line.strip.empty?
end
end
end


So I can run:

stream = StreamReader.new
stream.open_stream


and it prints out the data.

Now I am trying to open the feed with nodejs 6.4.0 but I can't get my head around it.

I think that I need a
net.Socket
and then pass it to a
tls.TLSSocket
which will return a duplex stream. But I can't figure out how to set it up. TLS is built on top of OpenSSL so it should be able to do the same thing.

This my setup so far:

var net = require('net');
var tls = require('tls');
var HOST = 'some.url.com';
var PORT = 1234;

var loginRequest = "<Request type='login' user='user' password='pass'></Request>"

//create net.Socket
var socket = new net.Socket();
socket.connect({port: PORT, host: HOST})

var tlsSocket = new tls.TLSSocket(socket,{requestCert:false})
tlsSocket.setEncoding("UTF-8")
//Listen for connect
socket.on("connect",function(){
console.log("connected to",HOST)
tlsSocket.write(loginRequest,function (){
console.log("request sent")
})
})
tlsSocket.on("error",function(err){
console.log("ERROR:",err)
})

tlsSocket.on("close",function(){
console.log("CLOSING")
})

tlsSocket.on("end",function(){
console.log("END")
})

tlsSocket.on("data",function(data){
console.log("DATA:",data)
})

tlsSocket.on("readable",function(){
console.log("SOMETHING TO READ")
console.log(tlsSocket.read())
})


It prints

connected to some.url.com
request sent
SOMETHING TO READ
null
END
CLOSING


As it says in https://nodejs.org/dist/latest-v6.x/docs/api/stream.html#stream_event_readable
readable
is emitted right before the
end
and data is
null
in this case. The providing company can't assist on that topic, only they know why. I need help to make it work like in the ruby snippet.

Any help appreciated.

Answer

As discovered through the discussion in the comments:

  • The issue is that the server needs a delimiter to find the end of the request sent and start processing it.

  • Adding a \n at the end of the request sent resolves the issue.