Introduction
The functionality of this article is similar to the one I wrote earlier (Linux select System call _2), which differs in how processes communicate. In the previous article, I was using pipelines, and this article I will use the socket interface.
Demand
The client sends a message to the server, and the server forwards the message to all clients after it receives the message.
Ideas
1. Server side maintains a linked list, which is used to store the client's contact information. The structure is as follows:
structstruct client_tag{ SA ct_addr; struct client_tag**pcnode;
2. The server creates a socket port for receiving messages sent by the client. Message categories are: Notification on-line, notification offline, and chat messages. Because of the different message categories, we use structs to encapsulate the messages sent by the client as follows:
#define type_on 1#define type_off 2#define type_chat 3
#define SIZE 1024
struct msg_tag{ int msg_type; int Msg_len; /* */ char*pmsg;
Note that the socket port created by the server needs to bind its own contact so that other clients can send messages (SendTo functions) to the server.
3. The server listens to its own socket port using the Select polling function. When the return value is 0 (no client sends a message within the polling time) or 1 (a signal is received, an error occurs), the polling continues, and when the return value is 1 o'clock, the client sends a message. We can get the client's contact information from the outgoing parameters of the Recvfrom function, which is processed according to the type of MSG received. If the MSG type is on-line, the contact of the client is added to the list, if the MSG type is offline, it is removed from the linked list, and if the MSG type is chat, the server forwards it to all clients.
Code
Let's talk about it tomorrow, the Big Brother first to see the fire shadow.
Linux network programming 5--using UDP protocol for group chat