[C] A very useful example of TCP communication between the server and the client

Source: Internet
Author: User
Tags set socket string back server port htons

This paper gives a very useful small example of TCP communication between the server and the client. Concrete implementation is very simple, but usually write a similar program, the specific steps are often forgotten, but also always check, for the time being written down, convenient for later reference.

(1) client program, write a file client.c, the content is as follows:

#include <stdlib.h>#include<stdio.h>#include<unistd.h>#include<string.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/inch.h>#include<netdb.h>/*Netdb is necessary for struct hostent*/#definePort 4321/* Server port */#defineMaxdatasize 100intMainintargcChar*argv[]) {    intSOCKFD, num;/*files Descriptors*/    CharBuf[maxdatasize];/*buf'll store received text*/    structHostent *he;/*structure that'll get information about remote host*/    structsockaddr_in server; if(ARGC! =2) {printf ("Usage:%s <ip address>\n", argv[0]); Exit (1); }        if((He=gethostbyname (argv[1]))==NULL) {printf ("gethostbyname () error\n"); Exit (1); }        if(Sockfd=socket (Af_inet,sock_stream,0))==-1) {printf ("socket () error\n"); Exit (1); } bzero (&server,sizeof(server)); Server.sin_family=af_inet; Server.sin_port=htons (PORT); Server.sin_addr= *((structIN_ADDR *) he->h_addr); if(Connect (SOCKFD,structSOCKADDR *) &server,sizeof(server)) ==-1) {printf ("Connect () error\n"); Exit (1); }
  
Char str[] = "horst\n"
if(Num=send (sockfd,str,sizeof (str),0))==-1) {printf ("Send () error\n"); Exit (1); } if(Num=recv (Sockfd,buf,maxdatasize,0))==-1) {printf ("recv () error\n"); Exit (1); } buf[num-1]=' /'; printf ("Server message:%s\n", BUF); Close (SOCKFD); return 0;}

(2) server-side, write server.c, content as follows

#include <sys/time.h>#include<stdlib.h>#include<stdio.h>#include<string.h>#include<unistd.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/inch.h>#include<arpa/inet.h>#definePORT 4321#defineBACKLOG 1#defineMaxrecvlen 1024intMainintargcChar*argv[]) {    CharBuf[maxrecvlen]; intLISTENFD, CONNECTFD;/*socket Descriptors*/    structsockaddr_in server;/*server ' s address information*/    structSOCKADDR_IN client;/*client ' s address information*/socklen_t Addrlen; /*Create TCP Socket*/    if(LISTENFD = socket (af_inet, Sock_stream,0)) == -1)    {        /*Handle Exception*/perror ("socket () error. Failed to initiate a socket"); Exit (1); }     /*Set socket option*/    intopt =so_reuseaddr; SetSockOpt (LISTENFD, Sol_socket, SO_REUSEADDR,&opt,sizeof(opt)); Bzero (&server,sizeof(server)); Server.sin_family=af_inet; Server.sin_port=htons (PORT); Server.sin_addr.s_addr=htonl (Inaddr_any); if(Bind (LISTENFD, (structSOCKADDR *) &server,sizeof(server)) == -1)    {        /*Handle Exception*/perror ("Bind () error."); Exit (1); }        if(Listen (LISTENFD, BACKLOG) = =-1) {perror ("Listen () error. \ n"); Exit (1); } Addrlen=sizeof(client);  while(1){        if(Connectfd=accept (LISTENFD, (structSOCKADDR *) &client, &addrlen)) ==-1) {perror ("Accept () error. \ n"); Exit (1); }        structTimeval TV; Gettimeofday (&TV, NULL); printf ("got a connection from client's IP%s, port%d at time%ld.%ld\n", Inet_ntoa (CLIENT.SIN_ADDR), htons (Client.sin_port), tv.tv_sec,tv.tv_usec); intiret=-1;  while(1) {Iret= Recv (Connectfd, buf, Maxrecvlen,0); if(iret>0) {printf ("%s\n", BUF); }Else{Close (CONNECTFD);  Break; }            /*Print client ' s IP and Port*/Send (CONNECTFD, buf, Iret,0);/*Send to the client welcome message*/}} close (LISTENFD); /*Close LISTENFD*/    return 0;}

(3) Compile and run

The above two programs are placed in the same directory, such as/home/horstxu/cprog/tcpcsmodel

The command line enters the directory $ cd/home/horstxu/cprog/tcpcsmodel

The command line executes $ gcc-o client client.c, which can be compiled out of the clients program.

The command line executes $ gcc-o Server SERVER.C, which can be compiled out of the service-side program.

The command line executes $./server, starting the server program.

At this point you may need to reopen a command-line window, go to the previous directory, execute $./client 127.0.0.1, start the client program, and you will see the results.

Client:

Server-side:

This program client will automatically exit, the server will not, so if you want to stop the server program, press the keyboard CTRL + C to stop directly at the command line interface.

The function of the program implementation is very simple, is the server listens to 4321 port, after the client establishes the TCP connection with it, sends the string "horst\n" to the service side, the service side prints, then passes the string back to the client, the client then prints out. The client then closes the connection exit while the server continues to listen on port 4321 for the next connection.

[C] A very useful example of TCP communication between the server and the client

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.