CreateTCPServer ( port )

Parameters

port - port number to listen on

Description

Creates a TCP server that listens for incoming connections on a port.

Returns a server handle, or 0 on failure - most often because the port is already in use by another program (or another copy of yours). The server does nothing by itself except listen: call AcceptTCPStream regularly to turn waiting connections into streams you can read and write.

Clients connect with OpenTCPStream using your machine's address and the same port. For testing you do not need two machines - one program (or two copies on one PC) can create a server and connect to itself via "127.0.0.1", the loopback address.

Close it with CloseTCPServer when the game stops listening.

See also: AcceptTCPStream, CloseTCPServer, OpenTCPStream, CountHostIPs.

Example

; CreateTCPServer Example
; -----------------------

; This program is server AND client at once: it listens on a
; port, then connects to itself over the loopback address.

port=4001

; CreateTCPServer returns a server handle, or 0 on failure
server=CreateTCPServer(port)
If server=0 Then
    Print "Could not listen on port "+port+" (it may be in use)"
Else
    Print "Server: listening on port "+port

    ; Open a client connection to our own server
    client=OpenTCPStream("127.0.0.1",port)
    If client=0 Then
        Print "Client: could not connect"
    Else
        Print "Client: connected to 127.0.0.1:"+port

        ; The server accepts the incoming connection - poll briefly,
        ; because AcceptTCPStream returns 0 until one has arrived
        accepted=0
        For try=1 To 100
            accepted=AcceptTCPStream(server)
            If accepted<>0 Then Exit
            Delay 10
        Next

        If accepted=0 Then
            Print "Server: no connection arrived"
        Else
            Print "Server: connection accepted"

            ; TCP streams read and write just like files
            WriteLine client,"Hello server!"
            Print "Client: sent 'Hello server!'"
            Print "Server: received '"+ReadLine$(accepted)+"'"

            CloseTCPStream accepted
        EndIf
        CloseTCPStream client
    EndIf
    CloseTCPServer server
    Print "Server: closed"
EndIf

Print ""
Print "Press any key to close the example"
WaitKey

End

Index