[C語言]一個很實用的服務端和客戶端進行TCP通信的實例


本文給出一個很實用的服務端和客戶端進行TCP通信的小例子。具體實現上非常簡單,只是平時編寫類似程序,具體步驟經常忘記,還要總是查,暫且將其記下來,方便以后參考。

 

(1)客戶端程序,編寫一個文件client.c,內容如下:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>  /* netdb is necessary for struct hostent */

#define PORT 4321   /* server port */

#define MAXDATASIZE 100

int main(int argc, char *argv[])
{
    int sockfd, num;    /* files descriptors */
    char buf[MAXDATASIZE];    /* buf will store received text */
    struct hostent *he;    /* structure that will get information about remote host */
    struct sockaddr_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 = *((struct in_addr *)he->h_addr);
    if(connect(sockfd, (struct sockaddr *)&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]='\0'; printf("server message: %s\n",buf); close(sockfd); return 0; }

 

(2)服務器端,編寫server.c,內容如下

#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/in.h>
#include <arpa/inet.h>

#define PORT 4321

#define BACKLOG 1
#define MAXRECVLEN 1024

int main(int argc, char *argv[])
{
    char buf[MAXRECVLEN];
    int listenfd, connectfd;   /* socket descriptors */
    struct sockaddr_in server; /* server's address information */
    struct sockaddr_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 */
    int opt = 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, (struct sockaddr *)&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,(struct sockaddr *)&client, &addrlen))==-1)
           {
            perror("accept() error. \n");
            exit(1);
           }

        struct timeval tv;
        gettimeofday(&tv, NULL);
           printf("You 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);
        
        int iret=-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)編譯運行

以上兩個程序放在同一個目錄下,比如 /home/horstxu/Cprog/tcpCSmodel

命令行進入該目錄 $ cd /home/horstxu/Cprog/tcpCSmodel

命令行執行 $ gcc -o client client.c ,可以編譯出客戶端程序。

命令行執行 $ gcc -o server server.c,可以編譯出服務端程序。

命令行執行 $ ./server,啟動server程序。

這時你可能需要重新打開一個命令行窗口,到剛才的目錄下,執行 $ ./client 127.0.0.1,啟動客戶端程序,就可以看到結果了。

客戶端:

服務器端:

本程序客戶端會自動退出,服務器不會,因此如果想停掉服務器程序,直接在命令行界面按鍵盤Ctrl+C停止。

 

程序實現的功能很簡單,就是服務器監聽4321端口,客戶端與之建立TCP連接后,再發送字符串“horst\n”到服務端,服務端打印出來,然后再把字符串傳回給客戶端,客戶端再打印出來。然后客戶端關閉連接退出,而服務端繼續監聽4321端口等待下一次連接。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM