TCP OPEN statement

Purpose

Enable an application to communicate with a TCP/IP server or client using the TCP protocol over Winsock.

Syntax

As a client:

TCP OPEN {PORT p& | srvc$} AT address$ AS [#] fNum& [TIMEOUT timeoutval&]

As a server:

TCP OPEN SERVER [ADDR ip&] {PORT p& | srvc$} AS [#] fNum& [TIMEOUT timeoutval&]

Remarks

Open a TCP/IP port or service for communication, either as a client or as a server.

SERVER

If the keyword server is included, the TCP port is opened as a TCP/IP server; otherwise, it is opened as a TCP/IP client.

ADDR ip&

As a server, if you specify the optional ADDR ip&, the TCP server monitors connections at the specified ip& address.  Otherwise, the primary IP address for the computer is used by default.

PORT p&

As a client, PORT identifies the server port that the client attempts to connect to.  As a server, PORT identifies the port the server will monitor for connection requests.  You may specify either a port number or a service name, but not both.

srvc$

If the port number is not specified, a service name must be specified instead.  A service name takes the form of "http", "smtp", or "ftp", etc.  You may specify either a port number or a service name, but not both.

AT address$

As a client, address$ identifies the address to connect with.  address$ can be a domain such as "powerbasic.com", or a dotted IP address in string form, such as "127.0.0.1".

fNum&

A file number such as #1, or a variable with a value obtained using the FREEFILE function.

TIMEOUT

The optional TIMEOUT value allows you to specify how long a TCP SEND, RECV, PRINT, or LINE operation should wait for completion, in milliseconds (mSec).  If the specified number of milliseconds elapses without a response, the TCP operation will fail, and the ERR system variable will be set to indicate a run-time Error 24 ("Device timeout").  The default timeout is 60000 milliseconds (60 seconds).

See also

TCP and UDP communications, FREEFILE, TCP ACCEPT, TCP CLOSE, TCP LINE INPUT, TCP NOTIFY, TCP PRINT, TCP RECV, TCP SEND, UDP OPEN

Example

' Client TCP/IP example - retrieve a web page

#COMPILE EXE

 

FUNCTION PBMAIN() AS LONG

  LOCAL Buffer$, Site$, File$, Entire_page$

  LOCAL Length&

 

  Site$ = "www.powerbasic.com"

  File$ = "http://www.powerbasic.com/support/forums/Forum2/HTML/000031.html"

 

  ' Connecting...

  TCP OPEN "http" AT Site$ AS #1 TIMEOUT 60000

 

  ' Could we connect to site?

  IF ERR THEN

      BEEP

      EXIT FUNCTION

  END IF

 

  ' Send the GET request...

  TCP PRINT #1, "GET " & File$ & " HTTP/1.0"

  TCP PRINT #1, "Referer: http://www.powerbasic.com/"

  TCP PRINT #1, "User-Agent: TCP OPEN Example (www.powerbasic.com)

  TCP PRINT #1, ""

 

  ' Retrieve the page...

  DO

    TCP RECV #1, 4096, Buffer$

    Entire_page = Entire_page + Buffer$

  LOOP WHILE ISTRUE LEN(Buffer$) AND ISFALSE ERR

 

  ' Close the TCP/IP port...

  TCP CLOSE #1

END FUNCTION