Sample code for 30+ languages & platforms
SQL Server

Receive a 4-byte Length Prefix from a Socket

See more Socket/SSL/TLS Examples

Demonstrates Socket.ReceiveCount, which reads a four-byte length prefix as a signed 32-bit integer. A return value of -1 indicates failure.

Background. Reading the length prefix first tells the application exactly how many bytes to read for the message body, which is a reliable way to know when a full message has arrived.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    DECLARE @socket int
    EXEC @hr = sp_OACreate 'Chilkat.Socket', @socket OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    --  Connect to the server using TLS.
    DECLARE @bTls int
    SELECT @bTls = 1
    DECLARE @maxWaitMs int
    SELECT @maxWaitMs = 5000
    EXEC sp_OAMethod @socket, 'Connect', @success OUT, 'example.com', 5000, @bTls, @maxWaitMs
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @socket, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @socket
        RETURN
      END

    --  Read a four-byte length prefix as a signed 32-bit integer (network byte order by default).  A
    --  return value of -1 indicates failure.
    DECLARE @messageLength int
    EXEC sp_OAMethod @socket, 'ReceiveCount', @messageLength OUT
    IF @messageLength < 0
      BEGIN
        EXEC sp_OAGetProperty @socket, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @socket
        RETURN
      END


    PRINT 'The peer will send ' + @messageLength + ' bytes.'

    EXEC @hr = sp_OADestroy @socket


END
GO