2.4 Basic TCP

2.4.1 TCP

NOTE: The TCP object has been deprecated and may not appear in newer versions of the instrument-control toolbox. Instead new code should use the tcpclient object.

A TCP connection can be opened using the tcp or tcpip function:

s = tcp("127.0.0.1", 80) 

The first parameter is the IP address to connect to. The second parameter is the port number. And optional timeout value can be also be provided.

A more matlab compatible function is available as tcpip to also open a tcp port:

s = tcpip("gnu.org", 80) 

The first parameter is a hostname or ip address, the second the port number. Additional parameter/value pairs can be provided after the port.

After creating the interface object, properties of the device can be set or retrieved using get or set functions or as property access.

s = tcp("127.0.0.1", 80)
oldtimeout = get(s, "timeout") # get timeout

set(s, "timeout", 10) # set the timeout
s.timeout = oldtimeout # also sets the timeout

The device can be written and read from using fread, fwrite and tcp_read and tcp_write functions.

tcp_write(s, "HEAD / HTTP/1.1\r\n\r\n")

val = tcp_read(s, 100, 500) # attempt to read 100 bytes

The device can be closed using fclose or tcp_close.

fclose(s)

2.4.2 TCP Client

The recommended method of creating a tcp connection is through the tcpclient object.

A TCP connection can be opened using the tcpclient function:

s = tcpclient("127.0.0.1", 80) 

The first parameter is the IP address or hostname to connect to. The second parameter is the port number.

Additional parameter/value pairs can be provided after the port.

After creating the interface object, properties of the device can be set or retrieved using get or set functions or as property access.

s = tcpclient("127.0.0.1", 80)
oldtimeout = get(s, "Timeout") # get timeout

set(s, "Timeout", 10) # set the timeout
s.Timeout = oldtimeout # also sets the timeout

The device can be written and read from using read and write functions.

write(s, "HEAD / HTTP/1.1\r\n\r\n")

val = read(s, 100) # attempt to read 100 bytes

The device can be closed by clearing the object variable.

clear s