Chatting

In its most basic form, Ncat simply moves bits from one place to another. This is all that is needed to set up a simple chat system. By default, Ncat reads from standard input and writes to standard output, meaning that it will send whatever is typed at the keyboard and will show on the screen whatever is received.

Two-user chat

host1$ ncat -l
host2$ ncat host1

With this setup, two users can communicate with each other. Whatever one types will appear on the screen of the other. Be aware that standard input is probably line-buffered so it may be necessary to press enter before a line is sent. Which side listens and which side connects is not important in this situation, except that the listener must start ncat first.

The above technique is limited to one-on-one conversations. If more users connect to the server, each one will effectively create a new chat channel with the server; none of the connecting users will hear each other. Multi-user chatting is easily supported using connection brokering with the --broker option (see the section called “Connection Brokering”). In broker mode, anything received on one connection is sent out to all other connections, so everyone can talk with everyone else.

When many users are chatting through a connection broker, it can be hard to know who is saying what. For these cases Ncat provides a simple hack to tell users apart. When the --chat option is given, connection brokering is automatically enabled. Each message received is prefixed with an ID before being relayed to all other clients. The ID is unique for each client connection, and therefore functions something like a username. Also, in chat mode any control characters are escaped so they won't mess up your terminal. The server is started with

server$ ncat -l --chat

Once the server is started, this is how the chat appears to one of the connected users. The lines that begin with <user<n>> are from other connected users. The line beginning with <user0> was sent by the listening broker.

client$ ncat server
<user6> Is anyone there?
I'm here.
<user5> Me too.
<user0> Go away, all of you.

The user IDs generated by Ncat are based on the file descriptor for each connection, and must be considered arbitrary. There is no way to choose a particular ID or make one persist across sessions. Nevertheless, --chat can come in handy for those quick multi-user conversations.