| tcp_server - server handle returned by CreateTCPServer |
|
Accepts a pending connection on a TCP server, returning a new stream. If a client is waiting to connect, you get back a TCP stream - a private two-way connection to that client, ready for the Read/Write commands. If nobody is waiting, the call returns 0 straight away (by default), so it is safe to poll once per frame in your main loop. TCPTimeouts can make it wait up to a chosen number of milliseconds instead. Each call accepts at most one client, and a server can accept many - keep the returned streams in a list to run a small multiplayer lobby or chat server. TCPStreamIP and TCPStreamPort tell you who connected. Close each stream with CloseTCPStream when that client is done; closing the server closes them all. See also: CreateTCPServer, CloseTCPStream, TCPTimeouts, TCPStreamIP. |
; AcceptTCPStream Example
; -----------------------
; This program is server AND client at once: it listens on a
; port, then connects to itself over the loopback address.
port=4003
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
; AcceptTCPStream returns the server's end of a new
; connection, or 0 if nobody is connecting right now -
; so a server normally polls it, as this loop does
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: AcceptTCPStream returned a stream after "+try+" poll(s)"
; The accepted stream reads and writes just like a file
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