Sample code for 30+ languages & platforms
PureBasic

Bind and Listen for Incoming Connections

See more Socket/SSL/TLS Examples

Demonstrates Socket.BindAndListen, which binds a TCP listener to a port and places it into listening mode, then accepts an incoming connection.

Background. The backlog argument bounds the queue of pending connections. When ClientIpAddress is empty, the listener binds to all interfaces. After listening, call AcceptNext to accept connections.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkSocket.pb"

Procedure ChilkatExample()

    success.i = 0

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

    ;  Bind a TCP listener to a port and place it into listening mode.  The 2nd argument is the backlog,
    ;  the maximum number of pending connections allowed to queue.
    success = CkSocket::ckBindAndListen(socket,5000,25)
    If success = 0
        Debug CkSocket::ckLastErrorText(socket)
        CkSocket::ckDispose(socket)
        ProcedureReturn
    EndIf

    ;  After the listener is established, accept the next incoming connection into a new Socket.
    connectedSock.i = CkSocket::ckCreate()
    If connectedSock.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkSocket::ckAcceptNext(socket,20000,connectedSock)
    If success = 0
        Debug CkSocket::ckLastErrorText(socket)
        CkSocket::ckDispose(socket)
        CkSocket::ckDispose(connectedSock)
        ProcedureReturn
    EndIf

    Debug "Accepted a connection."


    CkSocket::ckDispose(socket)
    CkSocket::ckDispose(connectedSock)


    ProcedureReturn
EndProcedure