The
is known by the title, this article is mainly about how to implement a C/S mode of the program with the language
Main function: Time loopback. The
client makes a request, server response time, and returns the server time to synchronize with the client.
Nonsense not much said, the following directly posted source code. The
code is as follows:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <e rrno.h> #include <time.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet
.h> void client_process (int connfd);
int main (int argc, char *argv[]) {int ret;
int LISTENFD;
int CONNFD;
struct sockaddr_in srvaddr;
struct sockaddr_in cliaddr;
Socklen_t Addrlen;
LISTENFD = socket (af_inet, sock_stream, 0);
if (LISTENFD = = 1) {perror ("socket");
Exit (Exit_failure);
} srvaddr.sin_family = Af_inet;
Srvaddr.sin_port = htons (8888);
SRVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
ret = bind (LISTENFD, (struct sockaddr *) &srvaddr, sizeof (SRVADDR));
if (ret = = 1) {perror ("bind");
Exit (Exit_failure);
RET = Listen (LISTENFD, 5);
if (ret = = 1) {perror ("listen");
Exit (Exit_failure); while (1) {memset (&cliaddr, 0, sizeOf (CLIADDR));
Addrlen = sizeof (CLIADDR);
CONNFD = Accept (LISTENFD, (struct sockaddr *) &cliaddr, &addrlen);
if (CONNFD!=-1) {printf ("A new client is comming\n");
Client_process (CONNFD);
printf ("disconnect\n");
Close (CONNFD);
else Perror ("accept");
Close (LISTENFD);
} void client_process (int connfd) {int ret;
Char buf[4096];
while (1) {memset (buf, 0, sizeof (BUF));
strcpy (buf, "Kevin@timeserver $");
ret = Write (CONNFD, buf, strlen (BUF) + 1);
if (ret = = 1) {perror ("write");
Return
} memset (buf, 0, sizeof (BUF));
ret = Read (CONNFD, buf, sizeof (BUF));
if (Ret > 0) {if (strcmp (buf, "time\r\n") = = 0) {time_t t;
memset (buf, 0, sizeof (BUF));
strcpy (buf, "Kevin@timeserver $");
ret = Write (CONNFD, buf, strlen (BUF) + 1);
if (ret = = 1) {perror ("write");
Return } time (&t);
strcpy (buf, CTime (&t));
ret = Write (CONNFD, buf, strlen (BUF) + 1);
if (ret = = 1) {perror ("write");
Return
}} else if (ret = 1) {perror ("read");
Return
else return;
}
}
Main process
1. Set up source program, input source code.
2. Open a terminal, compile and run the program. Compiler: GCC cs.c Run Program:./a.out
3. Open a new terminal, input: telnet localhost 8888
The main window effects are as follows:
4. Enter in child window: Time
The child window appears as follows:
5. Close the child window, the main window shows: The connection is disconnected.
The effect is as follows:
OK, the program is about here, I hope you like it, for everyone's learning help.