sending serialization stream on ngx.socket.tcp

50 views
Skip to first unread message

Hadi Abbasi

unread,
Apr 16, 2018, 9:54:26 AM4/16/18
to openresty-en
Hi there...
just I wanna send a bundle/structure by having 2 properties to my nodejs server api via ngx.socket.tcp on openresty for doing some processes on my content data (process depended on data type)!
1- file type that is string like 'img'  or  'json' or 'html' or other types
2- file content which can be ascii/utf8 string or can be an image file content (bytearray) or ...

I know that we can encode file content to base64 and then can send to another server api on json or xml or google protobuf format (having file type + file content)
but I wanna know if there is data serialization stream / buffer class on lua/nginx/openresty to append our different types of data and send to another server api (target server can be nodejs or php or ...)

so if I want to ask it easily, suppose that I want to send my structure data to nodejs server via ngx.socket.tcp that contains:
{
    file_type:always is string
    file_content: bytearray or normal string
}

thanks a lot...

tokers

unread,
Apr 16, 2018, 10:55:33 PM4/16/18
to openresty-en
Hello!

The only structure type that the ngx.socket.tcp can send is the array-like Lua table. So you need to serialize your structure via lua-cjson, lua-cmsgpack and etc by yourself.

tokers

unread,
Apr 16, 2018, 10:56:53 PM4/16/18
to openresty-en
The data inside the array-like Lua table will be jointed together as a string.

Hadi Abbasi

unread,
Apr 25, 2018, 1:37:25 AM4/25/18
to openresty-en
thanks a lot...
I have solved it just by lua concatation.
suppose that my data type and data content are: 
local dataType = x  -- string data
local dataContent=y  --binary bytearray data

so just we will try to send the data like this:

local sock = ngx.socket.tcp()
local ok, err = sock:connect("x.x.x.x","100")
if not ok then
ngx.log(ngx.ERR,"Failed to connect to minifier socket!")
return
end
local bytes, err = sock:send(dataType.. dataContent)
sock:settimeout(10000)

then we can receive it fron node and then we can retrieve both data (type and content) like:

var Buffer = require('buffer').Buffer;
var buf = new Buffer(data);  // dataType.. dataContent
var datatype = buf.slice(0, 3).toString();
var dataContent = buf.slice(3, data.length);
Reply all
Reply to author
Forward
0 new messages