What is TCP?
TCP is abbreviation of Transmission Control Protocol. TCP is one of the main protocols in TCP/IP networks. Whereas the IP protocol deals only with packets, TCP enables two hosts to establish a connection and exchange streams of data. TCP guarantees delivery of data and also guarantees that packets will be delivered in the same order in which they were sent.
To exchange data between two devices using TCP protocol, one device acts as TCP server, the other acts as TCP client. TCP server listens to wait for TCP connection request from TCP client. TCP Client actively make request for TCP connection to TCP server.
This example shows how to create a TCP server, which only accept one TCP connection at a time.
Hardware
- PHPoC Blue (+ USB WLAN) or PHPoC Black (+ Ethernet cable)
- Micro USB to USB Cable (to upload source code to PHPoC Device)
Quick Steps
Source code of this example is a part of PHPoC Support Packet (PSP). You need to:
- Download PHPoC Support Package.
- Upload example\net\01.php_task\tcp0_echo_ac to PHPoC Blue/Black.
- Modify port number if needed in task0.php file.
- Save the modified file.
- Configure network parameters (e.g. WiFi SSID, password, IP address ...).
Source Code
Source files includes:
- init.php: this file is run when PHPoC system is powered or reset. It is used to specify which file is run is system loop.
- task0.php: this file is run in system loop of PHPoC devices.
init.php
This file is run when PHPoC system is powered or reset. It is used to specify that task0.php is run is system loop.
PHP Code:
<?php
system("php task0.php");
?>
task0.php
[Full Code]
PHP Code:
<?php
if(_SERVER("REQUEST_METHOD"))
exit; // avoid php execution via http request
include_once "/lib/sn_tcp_ac.php";
echo "PHPoC example : TCP echo using auto connect library\r\n";
tcp_server(0, 14700);
$rwbuf = "";
while(1)
{
$rwlen = tcp_read(0, $rwbuf, tcp_txfree(0));
if($rwlen > 0)
tcp_write(0, $rwbuf);
}
?>
[Explanation]
Source code of this file does:
- Create a TCP server that listen on port 14700.
- Read data from TCP buffer.
- Send the received data back to the connected TCP client.
Test and Result
- Click "Run" button on PHPoC Debugger.
- In this example, PHPoC acts as TCP server. It needs to use TCP client to test . TCP client can be any kind of TCP client software/program on PC or smartphone, or another PHPoC device that run TCP client code.
- In my case, I use a TCP client app on Android.
- Install TCP client app on Android.
- Type IP address of PHPoC and port number used in the code.
- Click "Add" button to connect.
- Send messages from TCP client app to PHPoC
- See the echo message
See Also
- DNS lookup
- Sending email (SMTP)
- Sending email (ESMTP)
- MySQL - Inserting Data to Remote Server
- MySQL - Updating Data to Remote Server
- TCP Server - Multiple TCP Connections
- TCP Client - HTTP GET
Other Resources