|
server$ - machine to connect to, as a host name ("example.com") or dotted IP ("127.0.0.1") server_port - port number to connect to local_port (optional) - local port to bind this end to; 0 lets the system pick one (default) |
|
Opens a TCP connection to a server, returning a stream. Returns a stream handle, or 0 if the connection failed (no server listening, wrong address, no network). The stream works with all the usual stream commands: WriteLine/WriteInt and friends to send, ReadLine/ReadInt to receive, Eof and ReadAvail to watch its state. The other end is either a program using CreateTCPServer/AcceptTCPStream, or any internet service speaking a protocol you implement. Reads block until the requested data arrives, so on a live connection check ReadAvail before reading, and see TCPTimeouts for the safety limit that kills a stalled stream. To test networking on one PC, connect to "127.0.0.1" (loopback) - a second copy of your program, or the same program, can be the server. You rarely need local_port; leave it out unless a firewall setup demands a fixed outgoing port. Close the connection with CloseTCPStream when done. See also: CreateTCPServer, CloseTCPStream, ReadAvail, Eof, TCPTimeouts, DottedIP. |
; OpenTCPStream Example
; ---------------------
; This program is server AND client at once: it listens on a
; port, then connects to itself over the loopback address.
port=4002
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
; OpenTCPStream connects to a host and port and returns a
; stream handle, or 0 on failure. The host can also be a
; name such as "www.blitzbasic.com".
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"
; The opened stream reads and writes just like a file
WriteLine client,"Ping from the client"
Print "Client: sent 'Ping from the client'"
Print "Server: received '"+ReadLine$(accepted)+"'"
WriteLine accepted,"Pong from the server"
Print "Client: received '"+ReadLine$(client)+"'"
CloseTCPStream accepted
EndIf
CloseTCPStream client
EndIf
CloseTCPServer server
Print "Server: closed"
EndIf
Print ""
Print "Press any key to close the example"
WaitKey
End