18.`tcp/udp`学习

1.server.c服务器端的代码

#include
#include
#include
#include
#include
#include
#include
# define E_MSG(str, value) do{perror(str); return (value);} while(0);

int main(void){
    char buff[128];
    char IP[32];
    struct sockaddr_in serv, clie;
    socklen_t cli_len;

    int s_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(s_fd == -1) E_MSG("socket", -1);
    //对serv变量的成员进行初始化
    serv.sin_family = AF_INET;
    serv.sin_port = htons(8001);
    serv.sin_addr.s_addr = htonl(INADDR_ANY);
    int bb = bind(s_fd, (struct sockaddr *) &serv, sizeof(serv));
    if(bb == -1) E_MSG("bind", -1);
    //将s_fd设置为被动链接,监听客户端连接
    //将客户端的连接放入到未决队列中
    //此前要定义未决队列的长度
    listen(s_fd, 5);
    while(1){
        cli_len = sizeof(clie);
        //从未决队列中取出一个连接处理
        //返回这个连接的描述符,使用该描述符和客户端通信
        int c_fd = accept(s_fd, (struct sockaddr *)&clie, &cli_len);
        if(c_fd == -1) E_MSG("accept", -1);
        //到此时,三次握手成功,可以传输数据
        //从c_fd中读取客户端发来的数据
        //二进制转换成字符
        inet_ntop(AF_INET, &clie.sin_addr, IP, 32);
        printf("Cleint ip: %s\n", IP);
        int r = read(c_fd, buff, 128);
        int i;
        for(i = 0; i < r; i++){
            buff[i] = toupper(buff[i]);
        }
        //将处理结果回送
        write(c_fd, buff, r);
        close(c_fd);
    }
    return 0;
}

2.client.c

#include
#include
#include
#include
#include

int main(void){
    char buff[128];
    struct sockaddr_in serv;
    char *msg = "hello sky walker...\n";
    //create an socket connection, return file descriptor;
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if(fd == -1) return -1;

    serv.sin_family = AF_INET;
    serv.sin_port = htons(8001);
    //二进制转换
    inet_pton(AF_INET, "127.0.0.1", &serv.sin_addr);
    //使用fd向服务器发起连接
    int c = connect(fd, (struct sockaddr *)&serv, sizeof(serv));
    if(c == -1) return -1;
    //三次握手成功,向服务器发送数据
    write(fd, msg, strlen(msg) + 1);
    //等待服务器回应
    int r = read(fd, buff, 128);
    write(1, buff, r);
    close(fd);

    return 0;
}

你可能感兴趣的:(18.`tcp/udp`学习)