TCP – Transmission Control Protocol, is the most used network-transport layer protocol. Most popular higher level protocols such as HTTP, FTP, POP, SMTP, SSH, MQTT and others are based on TCP.
The other transmission level protocol, relevant for developers, is UDP.
TCP is connection based – stateful, and is reliable. The communication is done using a full duplex stream.
The data will be received in the correct order and exactly as it was sent. If there are any problems then the connection will be broken.
UDP, on the other hand, is connectionless – stateless, and not 100% reliable.
A TCP connection is always done with a connection request that is made by the client to the listening server. The server is identified by its ip address (or host name which is resolved to an ip addres) and port number. The port is a number between 0 to 65535 where 0 – 1023 are usually reserved to the OS.
Once a connection is established, the communication is done between two symmetrical sockets.
The server side is implemented in B4X with the ServerSocket type and the client side with the Socket type. Both belong to the internal Network library. Similar APIs are also available in B4R.
Once a connection is made we can write or read from the stream. We never do it on the main thread. This will cause our apps to freeze. The correct way to do it is with AsyncStreams from the RandomAccessFile library.
- Windows firewall blocks incoming connections by default. You must add a rule if you want to allow clients to connect to the PC.
- TCP is a low level protocol. In most cases it is a mistake to use it directly. Simpler and “better” alternatives: MQTT and B4J jServer.
- Example of network communication: https://www.b4x.com/android/forum/threads/b4x-b4xpages-network-asyncstreams-b4xserializator.119011/#content
- Example of a MJPEG server that supports multiple clients: https://www.b4x.com/android/forum/threads/73792/#content
- Example of FTP server that supports multiple clients: https://www.b4x.com/android/forum/threads/74320/#content
- A connection is identified by 4 values: source ip, source port, destination ip, destination port. This means that a server can listen on a single port and allow multiple clients to connect and communicate.