Send byte array via TCP

Q&A's, tips, howto's
Locked
csfreebird
Posts: 107
Joined: Tue Jan 15, 2013 11:54 am
Location: China, Beijing
Contact:

Send byte array via TCP

Post by csfreebird »

Hello
I want to send two bytes which represent an unsigned short in big-endian to server via TCP. But net-send only supports string parameter.
Could anyone tell me how to do this?

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Re: Send byte array via TCP

Post by cormullion »

Does pack help?

bairui
Posts: 64
Joined: Sun May 06, 2012 2:04 am
Location: China
Contact:

Re: Send byte array via TCP

Post by bairui »

I'm going to guess here, csfreebird, that you can use the (pack ...) and (unpack ...) functions for this. See the newLISP User Manual for these functions. From a quick look, it would seem you'd use:

Code: Select all

(pack ">d" your_short)
For a signed big-endian short.

Heh... and on clicking Submit, it seems that Cormullion agrees. :)

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Re: Send byte array via TCP

Post by cormullion »

i know nothing about TCP :)

csfreebird
Posts: 107
Joined: Tue Jan 15, 2013 11:54 am
Location: China, Beijing
Contact:

Re: Send byte array via TCP

Post by csfreebird »

Thanks for so quick reply.
But after packaging my short integer, I need a way to send the bytes to server via TCP.
net-send always needs a string.
And the pack returns a string too.

Code: Select all

>(pack ">d" 5)
"\000\005"
Which API could let me to send my byte array?
I am new to newLISP.

bairui
Posts: 64
Joined: Sun May 06, 2012 2:04 am
Location: China
Contact:

Re: Send byte array via TCP

Post by bairui »

I have never done net coding, but I thought that was exactly what the (pack ...), (unpack ...) pair were for - to be able to send binary values encoded as strings to be decoded back into their proper forms at the other end. No?

csfreebird
Posts: 107
Joined: Tue Jan 15, 2013 11:54 am
Location: China, Beijing
Contact:

Re: Send byte array via TCP

Post by csfreebird »

It works now.

Code: Select all

> (set 'socket (net-connect "localhost" 8889))
16
> (set 'size (pack ">d" 19))
"\000\019"
> (net-send socket size)
2
pack returns a string buffer that contains my two bytes, net-send sends the string to server.
My C++ server got two bytes, 0 and 19.
Thanks.

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Re: Send byte array via TCP

Post by cormullion »

Good work guys. If you could answer the question on Stack Overflow, that would look good...!

csfreebird
Posts: 107
Joined: Tue Jan 15, 2013 11:54 am
Location: China, Beijing
Contact:

Re: Send byte array via TCP

Post by csfreebird »

It's done.
Will go ahead with this.
I am about to simulate over 20,000 devices using newLISP, they will be used to test against my TCP server.

Locked