Server Code:
Client Code:
Explanation:
Server Code:
- Setup:
- Creates a socket using
socket()
. - Configures server address
serverAddr
withAF_INET
(IPv4),INADDR_ANY
(binds to all available interfaces), andPORT
. - Binds the socket to the address using
bind()
. - Listens for incoming connections with
listen()
.
- Creates a socket using
- Handling Clients:
- Uses
accept()
to accept incoming client connections. - Spawns a new thread to handle each client connection. The
handleClient()
function:- Receives messages from the client.
- Prints the received message.
- Sends the same message back to the client (echo server).
- Closes the client socket when done.
- Uses
- Error Handling:
- Checks for errors at each step and prints appropriate error messages using
perror()
.
- Checks for errors at each step and prints appropriate error messages using
Client Code:
- Setup:
- Creates a socket with
socket()
. - Configures server address
serv_addr
withAF_INET
andPORT
. - Converts IP address to binary form with
inet_pton()
and connects to the server usingconnect()
.
- Creates a socket with
- Interaction:
- Sends user input to the server with
send()
. - Receives and prints the server’s response with
recv()
. - Exits the loop if the user types “exit”.
- Sends user input to the server with
- Error Handling:
- Checks for connection errors and displays messages if needed.
How to Run:
Compile and Run the Server:
Compile and Run the Client:
Testing:
- Start the server first.
- Then, run the client.
- Type messages in the client and observe that they are echoed back by the server.
- Checks for connection errors and displays messages if needed.