Streaming socket Client server-side code implementation based on Linux platform

Source: Internet
Author: User
Tags socket error htons

(1) The server segment code is as follows:

#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include < string.h> #include <netdb.h> #include <sys/types.h> #include <time.h> #include <sys/socket.h > #include <arpa/inet.h> #define BUFSIZE 512/* * ERROR report */static void bail (const char *on_what) {fputs (strerror (er    Rno), stderr);    Fputs (":", stderr);    Fputs (On_what, stderr);      FPUTC (' \ n ', stderr); Exit (1);}                  int main (int argc, char *argv[]) {int sockfd;                  /* Server sockets */int new_fd;  /* Server Connection Socket */struct sockaddr_in server_addr;  /* Server listener Socket */struct sockaddr_in client_addr;    /* Client IP Address */socklen_t size;    int portnumber;  Char Reqbuf[bufsize];   /* Apply Receive Cache */char dtfmt[bufsize];        /* Date-time result String */time_t TD;    /* Current date and time */struct TM TM;    /* Date Time structure body */int z;        if (argc! = 2) {fprintf (stderr, "Usage:%s portnumber\a\n", argv[0]); EXIT (1);        } if ((PortNumber = Atoi (argv[1)) <0) {fprintf (stderr, "Usage:%s portnumber\a\n", argv[0]);    Exit (1); }/* Create a Server listener socket */if ((SOCKFD = socket (pf_inet, sock_stream, 0)) = =-1) {fprintf (stderr, "Socket error:%s\a\        N ", Strerror (errno));    Exit (1);    */* Prepare the IP address and port for the listener socket */memset (&server_addr, 0, sizeof server_addr);    server_addr.sin_family = af_inet;     SERVER_ADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);    Server_addr.sin_port = htons (portnumber); /* Bind the socket to the specified address and port */if (Bind (SOCKFD, (struct sockaddr *) (&AMP;SERVER_ADDR), sizeof SERVER_ADDR        ) = =-1) {fprintf (stderr, "Bind Error:%s\a\n", Strerror (errno));    Exit (1); }/* Monitor */if (listen (SOCKFD, +) = =-1) {fprintf (stderr, "Listen error:%s\n\a", S        Trerror (errno));    Exit (1);    } printf ("Waiting for the client ' s request...\n");  /* Server main loop processing */while (1) {      size = sizeof (struct sockaddr_in); /* Receive a client connection and create a server connection socket */if (NEW_FD = Accept (SOCKFD, (struct sockaddr *) (&AMP;CLIENT_ADDR), &A             mp;size)) = =-1) {fprintf (stderr, "Accept Error:%s\a\n", Strerror (errno));        Exit (1);        } fprintf (stdout, "Server got connection from%s\n", Inet_ntoa (CLIENT_ADDR.SIN_ADDR)); for (;;) {/* reads the datetime request from the client, if the client does not send the request, * The server will block */z = read (new_fd, Reqbuf, siz            EOF reqbuf);            if (Z < 0) bail ("read ()"); /* The server checks if the client has closed the socket, and the read operation * returns 0 (EOF).               If the client closes its socket, the server * will execute close to end this connection and then start receiving a connection request for the next client */if (z = = 0) {                Close (NEW_FD);            Break            }/* * Add a null character to the end of the request connection string to form the complete request day * Period Time String */reqbuf[z] = 0; /* * Get the current date and time of the server * * (&AMP;TD);            TM = *localtime (&AMP;TD);                /* * Generate an answer string based on the format string of the request date strings */strftime (DTFMT,/* Formatted results */sizeof DTFMT, REQBUF,/* Client request format string */&AMP;TM);/* Send formatting results to client */z = write (new_fd, DTF             MT, strlen (DTFMT));          if (Z < 0) bail ("write ()");     }          }            }

(2) Client code:

 #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include < netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <arpa/     Inet.h> #define BUFSIZE-static void bail (const char *on_what) {fputs (Strerror (errno), stderr);     Fputs (":", stderr);     Fputs (On_what, stderr);    FPUTC (' \ n ', stderr); Exit (1);                             }int Main (int argc, char *argv[]) {int sockfd;    /* Client socket */char buf[bufsize];     struct sockaddr_in server_addr;    /* Server IP address */struct hostent *host;    int portnumber;    int nbytes;    int z;                 Char Reqbuf[bufsize]; /* Client Request format string */if (argc! = 3) {fprintf (stderr, "Usage:%s hostname portnumber\a\n", AR        Gv[0]);    Exit (1);       } if ((host = gethostbyname (argv[1)) = = NULL) {fprintf (stderr, "GetHostName error\n");    Exit (1); } if ((PortNumber = Atoi (argv[2])) < 0) {fprintf (stderr, "Usage:%s hostname portnumber\a\n", argv[0]);    Exit (1);                         }/* Create socket */if ((SOCKFD = socket (pf_inet, sock_stream, 0)) = =-1) {fprintf (stderr, "Socket Error:%s\a\n",        Strerror (errno));    Exit (1);    }/* Create server address */memset (&server_addr, 0, sizeof server_addr);    server_addr.sin_family = af_inet;    Server_addr.sin_port = htons (portnumber);    server_addr.sin_addr = * (struct in_addr *) host->h_addr); /* Linked server */if (connect (SOCKFD, struct sockaddr *) (&AMP;SERVER_ADDR), sizeof server_addr) = =-1) {fprintf        (stderr, "Connect Error:%s\a\n", Strerror (errno));    Exit (1);    } printf ("Connected to server%s\n", Inet_ntoa (SERVER_ADDR.SIN_ADDR)); /* * Client program main loop, enter ' quit ' to exit */for (;;) {/* Prompt for Date time format string */fputs ("\nenter format string (^d or ' quit ' to exit):", StdoUT);            if (!fgets (reqbuf, sizeof reqbuf, stdin)) {printf ("\ n");      Break        /* EOF */* * Add a null string as the end of the datetime request string, and also remove the trailing newline at the same time */z = strlen (reqbuf);        if (Z > 0 && reqbuf[--z] = = ' \ n ') reqbuf[z] = 0;        if (z = = 0)/* Client input entered enter */continue; /* * Enter quit Exit */if (!strcasecmp (Reqbuf, "quit")) {printf ("Press any key to end client.            \ n ");            GetChar ();        Break        }/* * Send date Time request string to server, note that the request message is stripped of the null character */z = write (sockfd, Reqbuf, strlen (REQBUF)); printf ("Client has sent??" %s??        To the sever\n ", reqbuf);        if (Z < 0) bail ("write ()"); /* * Read the server's reply from the client socket */if ((nbytes = Read (SOCKFD, buf, sizeof buf)) = =-1) {fprintf (s            Tderr, "Read Error:%s\n", Strerror (errno));        Exit (1);  }        /*      * If the server closes the link for one reason, the customer segment needs to handle this event */if (nbytes = = 0) {/*????           EOF */printf ("Server has closed the socket.\n");            printf ("Press any key to exit...\n");            GetChar ();        Break       } Buf[nbytes] = ' + ';            /* * Output Date Time results */printf ("Result from%s port%u: \n\t '%s ' \ n", Inet_ntoa (SERVER_ADDR.SIN_ADDR),   (unsigned) Ntohs (server_addr.sin_port), buf);   } close (SOCKFD); return 0;}

(3) Execution procedure




Streaming socket Client server-side code implementation based on Linux platform

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.