Making a Chat TCP IPv4 POSIX socket
We’ll build a chat on LAN, after using a centralized tunneling service we communicate them on the Internet and share them with decentralized tunneling after.
LAN chat
We don’t develop two files, one for a client, and another for a server. The same process should be client and server.
So, it means that the socket tries to start a connection with a peer connection, when it fails then it waits until a peer connection sends a signal.
if (connection) {
// I am peer client, it sent a signal to peer.
} else {
// I am peer server, I wait until a peer sends a signal
}
stateDiagram-v2
[*] --> SocketCreation
SocketCreation --> SocketConnection: if argc == 3
SocketCreation --> SocketBinding: if argc == 1
SocketConnection --> SocketBinding: connection failed
SocketConnection --> PassiveSocket: successful connection
PassiveSocket --> [*]
SocketBinding --> SocketListening
SocketListening --> SocketAccepting
SocketAccepting --> ActiveSocket
Error --> [*]
ActiveSocket --> [*]
When two peers are connected, they can send and receive messages from different threads.
From peer 1. It is a passive socket.

From peer 2. It is an active socket.

Peer 2 sends a message to peer 1


Peer 1 sends a message to peer 2


Your chat on the Internet with centralized tunnels.
You must install ngrok in order to make a tunnel over the Internet. Now, use its command, where [PORT] is the passive socket port.
ngrok TCP [PORT]

And now the active socket port connects to passive internet using the IP and port provided by ngrok.
ping [uri] # where [uri] is the ngrok provided

And now we connect them


Ready!
Repository
Compilation
make
Use
A passive socket is
./chat.out
An active socket is
./chat.out [SERVER PORT] [PORT]