A basic chat application having client-server architecture, developed using multi-threaded socket programming.
- Single multi-threaded server to handle multiple clients.
- A client can talk to another client during a session if the requested client is free.
- All messages are sent through TCP socket.
- One mutex mapped to each client to avoid race condition while connecting two clients.
- Clone the repo and change directory
git clone https://github.com/anand-2020/socket-chat-in-linux.git
cd socket-chat-in-linux
- Compile the
server.cpp
andclient.cpp
files
g++ server.cpp -o server -lpthread
g++ client.cpp -o client -lpthread
- Run the server
./server <port_no>
- Run the clients
For each client open 2 terminals . Why ? 😕
Role of terminals
- Terminal 2 is used to compile, run and send command(or message) to server(or peer connected client).
- Terminal 1 displays the chat messages (both sent and recieved). Client need NOT to type anything in this terminal.
- The stdout of client program is redirected to terminal 2 using > operator. `tty` of terminal 1 is needed for this.
If output is not redirected, then consider the following scenario:
- client x1 and client x2 are chatting with each other
- client x1 is typing some messages and in between client x2 sends some message.
- Now this recieved messaged will get printed on the same line on which client x1 has its partially typed message. And this is definitely not desired.
Hence, for each client, the chat message(both sent and recieved) are directed to show in another terminal.
- Terminal 1
tty
- Terminal 2
./client <host_name> <port_no> > <output-of-tty-in-terminal-1>
- Server side
get clients | show status(FREE / BUSY with whom) of active clients |
get free_clients | show list of free clients |
- Client side
get clients | get status(FREE / BUSY) of active clients |
connect X | connect with client X |
goodbye | disconnect with currently connected client. |
close | close the connection with server |