Compile with
gcc -Wall -pedantic -Wextra -Werror client.c socket.c -o client && gcc server.c socket.c -o server -lpthread
(Should produce no warnings.)
This simple socket example demonstrates how to run a server and multiple clients. Client can be started with or without a parameter. If a parameter is used it is sent to the server after which client exits. If no parameter is supplied client enters a loop asking for messages to send from the user. typing "quit" quits the client. First client started acts as a control channel, typing "quit" into it also quits server process. This is because that server listener is created from the main thread and exiting it will also exit the main thread ending the program.
Output should look something like shown below.
Server:
Starting socket server.
Creating local socket.
Waiting for client.
Client 4 connected to server.
Message received from socket 4: barf
Sending message barf to 4 of length 4.
Client socket 4 closed.
Client:
Connecting to server.
Connecting to local socket.
Connected to socket 3.
Sending message barf to 3 of length 4.
Message received from socket 3. Length 4. barf
Server:
Starting socket server.
Creating local socket.
Waiting for client.
Client 4 connected to server.
Creating local socket.
Waiting for client.
Client 6 connected to server.
Creating local socket.
Waiting for client.
Message received from socket 4: foobar
Sending message foobar to 4 of length 6.
Message received from socket 6: barbar
Sending message barbar to 6 of length 6.
Message received from socket 6: quit
Sending message quit to 6 of length 4.
Received quit from 6
Message received from socket 4: quit
Sending message quit to 4 of length 4.
Received quit from 4
Client 1:
Connecting to server.
Connecting to local socket.
Connected to socket 3.
Message: foobar
Sending message foobar to 3 of length 6.
Message received from socket 3. Length 6. foobar
Message: quit
Sending message quit to 3 of length 4.
Message received from socket 3. Length 4. quit
Client 2:
Connecting to server.
Connecting to local socket.
Connected to socket 3.
Message: barbar
Sending message barbar to 3 of length 6.
Message received from socket 3. Length 6. barbar
Message: quit
Sending message quit to 3 of length 4.
Message received from socket 3. Length 4. quit