zoukankan      html  css  js  c++  java
  • 对一段C语言服务器代码的详解

    • 服务端----其代码如下
    #include <stdio.h>
    #include<stdlib.h>
    #include<sys/socket.h>
    #include<unistd.h>
    #define SERV_PORT 9898
    #define SERV_IP "127.0.0.1"
    #include<ctype.h>
    #include<arpa/inet.h>
    int main()
    {
    
        int lfd,cfd,n,i;
        char buf[BUFSIZ];
        struct sockaddr_in serv_addr,client_addr;
        socklen_t client_addr_len;
        lfd=socket(AF_INET,SOCK_STREAM,0);//
        serv_addr.sin_family=AF_INET;
        serv_addr.sin_port=htons(SERV_PORT);
        serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);//
        bind(lfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
        listen(lfd,128);//128 is uplimit
        client_addr_len=sizeof(client_addr);
        cfd=accept(lfd,(struct client_addr*)&client_addr,&client_addr_len);//will recv fd and return fd
        while(1)
        {
            n=read(cfd,buf,sizeof(buf));
            for(i=0;i<n;i++)
            {
                buf[i]=toupper(buf[i]);
            }
            write(cfd,buf,n);
        }
    
        printf("Hello World!
    ");
        return 0;
    }

    测试:打开一个终端输入 nc 127.0.0.1 9898

    • 客户端
    #include<stdio.h>
    #include<arpa/inet.h>
    #include<stdlib.h>
    #include<unistd.h>
    
    #include<sys/socket.h>
    #include<string.h>
    #define SERV_IP "127.0.0.1"
    #define SERV_PORT 9898
    int main()
    {
        int cfd,n;
        char buf[BUFSIZ];
        struct sockaddr_in serv_addr;
        socklen_t serv_addr_len;
        memset(&serv_addr,0,sizeof(serv_addr));
        cfd=socket(AF_INET,SOCK_STREAM,0);
        serv_addr.sin_family=AF_INET;
        serv_addr.sin_port=SERV_PORT;
        inet_pton(AF_INET,SERV_IP,&serv_addr.sin_addr.s_addr);
        connect(cfd,(struct sockaddr_in *)&serv_addr,sizeof(serv_addr));
        while(1)
        {
            fgets(buf,sizeof(buf),stdin);//gets is out-of-date;use fgets readline until the end, back with 
            write(cfd,buf,strlen(buf));
            n=read(cfd,buf,sizeof(buf));
            write(STDOUT_FILENO,buf,n);
        }
    
        close(cfd);
        return 0;
    }
  • 相关阅读:
    树形视图和列表视图中的HitTest
    VC++中隐藏代码
    C++指针&引用简笔
    自动化流程学习笔记
    xampp for linux遇见的几个问题
    django用户验证模块核心
    win+r 快捷
    python 获取桌面路径
    我的linux常用操作
    个人悟出的一些观点
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/12123879.html
Copyright © 2011-2022 走看看