Linux 多进程程序调试实例(七) -- 套接字

套接字

套接字介绍

  • socket 套接字是支持不同主机不同进程之间的通信

套接字函数

套接字编程

  • 在服务端,套接字编程顺序为 套接字创建(socket),套接字绑定(bind),套接字监听(listen),循环等待套接字链接(accept),读写消息(write、read),套接字关闭(close);
  • 在客户端,套接字编程顺序为 套接字创建(socket),套接字链接(connect),写读消息(write、read),套接字关闭(close);

代码

// server.cpp
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<cstdio>
#include<cstdlib>
#include<signal.h>

int main()
{
    int server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

    sockaddr_in server_addr, client_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(9736);

    bind(server_sockfd, (sockaddr*)&server_addr, sizeof(server_addr));

    listen(server_sockfd, 5);

    signal(SIGCHLD, SIG_IGN);

    while (1)
    {
        // char ch = '\0';
        char str[1024] = {0};
        socklen_t  client_len = sizeof(client_addr);
        printf("Server waiting\n");
        int client_fd = accept(server_sockfd, (sockaddr*)&client_addr, &client_len);

        if(0 == fork()){
            read(client_fd, &str, 1024);
            printf("receive message from client_fd : %d, message : %s\n", client_fd, str);
            sleep(1);
            write(client_fd, str, 1024);
            close(client_fd);
            exit(0);
        }
        else{
            close(client_fd);
        }
    }
    
}
// client.cpp
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstdio>
#include<cstdlib>
#include<signal.h>

int main()
{
    int server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(9736);
    int len = sizeof(address);

    int result = connect(server_sockfd, (sockaddr*)&address, len);

    if(-1 == result){
        perror("ops: client\n");
        exit(1);
    }

    char str[1024] = {0};
    char rece_str[1024] = {0};
    printf("please input you want to type:%s",str);
    scanf("%s", str);
    write(server_sockfd, &str, 1024);
    read(server_sockfd, rece_str, 1024);

    printf("message from server:%s\n",rece_str);
    close(server_sockfd);
    return 0;
}

调试

两个独立的进程调试,和普通函数调试过程一样

posted @ 2023-02-08 10:18  王清河  阅读(56)  评论(0编辑  收藏  举报