Sample code for 30+ languages & platforms
PureBasic

Send StringBuilder Contents over a Socket

See more Socket/SSL/TLS Examples

Demonstrates Socket.SendSb, which encodes the contents of a StringBuilder using StringCharset and sends the resulting bytes.

Background. Text send and receive operations encode and decode bytes using the StringCharset property. For plain ASCII or UTF-8 protocols, setting StringCharset to utf-8 is a safe default.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkSocket.pb"

Procedure ChilkatExample()

    success.i = 0

    socket.i = CkSocket::ckCreate()
    If socket.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Connect to the server using TLS.  The 3rd argument enables the TLS handshake after the TCP
    ;  connection succeeds; the 4th is the maximum time to wait, in milliseconds.
    bTls.i = 1
    maxWaitMs.i = 5000
    success = CkSocket::ckConnect(socket,"example.com",5000,bTls,maxWaitMs)
    If success = 0
        Debug CkSocket::ckLastErrorText(socket)
        CkSocket::ckDispose(socket)
        ProcedureReturn
    EndIf

    ;  StringCharset controls the character encoding used when sending and receiving text.
    CkSocket::setCkStringCharset(socket, "utf-8")

    ;  Build the text to send in a StringBuilder, then send its contents.
    sb.i = CkStringBuilder::ckCreate()
    If sb.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(sb,"SET temperature 21" + Chr(13) + Chr(10))

    success = CkSocket::ckSendSb(socket,sb)
    If success = 0
        Debug CkSocket::ckLastErrorText(socket)
        CkSocket::ckDispose(socket)
        CkStringBuilder::ckDispose(sb)
        ProcedureReturn
    EndIf

    Debug "Message sent."


    CkSocket::ckDispose(socket)
    CkStringBuilder::ckDispose(sb)


    ProcedureReturn
EndProcedure