Xbase++
Xbase++
Socket Send/Receive 16-bit Integers
Demonstrates sending and receiving 16-bit integers over a socket connection using either big-endian or little-endian byte ordering.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oSock
LOCAL nUseTls
LOCAL nPort
LOCAL nMaxWaitMs
LOCAL nValue
LOCAL nBigEndian
LOCAL cHexStr
nSuccess := 0
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
oSock := CreateObject("Chilkat.Socket")
// --------------------------------------------------------------------
// This example uses the public TCP echo service at https://tcpbin.com/
// --------------------------------------------------------------------
nUseTls := 0
nPort := 4242
nMaxWaitMs := 5000
nSuccess := oSock:Connect("tcpbin.com", nPort, nUseTls, nMaxWaitMs)
IF (nSuccess == 0)
? oSock:LastErrorText
oSock:destroy()
RETURN
ENDIF
// Wait a max of 2 seconds for a response..
oSock:MaxReadIdleMs := 2000
// Send a 16-bit integer using big-endian byte ordering (also called network byte order)
// 12022 decimal = 2EF6 hex
nValue := 12022
nBigEndian := 1
oSock:SendInt16(nValue, nBigEndian)
// Send it again, because we'll read it two different ways..
oSock:SendInt16(nValue, nBigEndian)
// The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
oSock:SendByte(10)
// Let's see hex values of the 2 bytes sent in network byte order (big-endian)
// (The echo server sends back exactly the bytes received.)
cHexStr := oSock:ReceiveNBytesENC(2, "hex")
// In the big-ending byte order, the byte order is most significant byte to least significant,
// therefore we should see the bytes in the order 0x2E 0xF6.
? "Expecting big-endian 2EF6"
? cHexStr
// Let's read directly to an integer..
nSuccess := oSock:ReceiveInt16(nBigEndian, 1)
? "Expecting 12022"
? "Received: " + Str(oSock:ReceivedInt)
// Consume the LF that gets echoed back..
oSock:ReceiveByte(1)
// --------------------------------------------------------------------
// Let's do the same thing, but with little-endian byte ordering.
? "----"
// 12022 decimal = 2EF6 hex, but little-endian byte ordering will send the bytes in the order 0xF6 0x2E
nValue := 12022
nBigEndian := 0
oSock:SendInt16(nValue, nBigEndian)
oSock:SendInt16(nValue, nBigEndian)
oSock:SendByte(10)
cHexStr := oSock:ReceiveNBytesENC(2, "hex")
? "Expecting little-endian F62E"
? cHexStr
nSuccess := oSock:ReceiveInt16(nBigEndian, 1)
? "Expecting 12022"
? "Received: " + Str(oSock:ReceivedInt)
// Consume the LF that gets echoed back..
oSock:ReceiveByte(1)
oSock:Close(1000)
// Output:
// Expecting big-endian 2EF6
// 2EF6
// Expecting 12022
// Received: 12022
// ----
// Expecting little-endian F62E
// F62E
// Expecting 12022
// Received: 12022
oSock:destroy()