分类 网络编程 下的文章

TCP/IP网络编程,一个简单的并发TCP server


本文在上篇文章的基础上,实现了服务端的并发,支持多个客户端同时连接到服务端上。

实现并发连接的主要技术是利用fork函数为每个客户端连接分配一个单独的进程进行处理。

server.cpp代码

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

constexpr uint32_t MAXLEN = 4096;
constexpr uint16_t PORT = 6666;
constexpr uint32_t MAX_CONN_MUN = 10;

inline void PrintErr()
{
    printf("errno = %s\n", strerror(errno));
}

int CreateSocket(uint16_t port, int& listen_fd)
{
    listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_fd == -1) {
        PrintErr();
        return -1;
    }

    sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(port);

    int ret = bind(listen_fd, reinterpret_cast<sockaddr*>(&serv_addr), sizeof(serv_addr));
    if (ret == -1) {
        PrintErr();
        return -1;
    }

    ret = listen(listen_fd, MAX_CONN_MUN);
    if (ret == -1) {
        PrintErr();
        return -1;
    }

    return 0;
}

void StrEcho(int sock_fd)
{
    char buf[MAXLEN];
    ssize_t n;
again:
    while ((n = read(sock_fd, buf, sizeof(buf))) > 0) {
        printf("rev msg: %s\n", buf);
        write(sock_fd, buf, n);
    }
    if (n < 0 && errno == EINTR) {
        goto again;
    } else if (n < 0) {
        printf("read error\n");
    }
}

int main()
{
    int listen_fd;
    int ret = CreateSocket(PORT, listen_fd);
    if (ret != 0) {
        exit(0);
    }

    sockaddr_in cliaddr;
    socklen_t clilen;
    pid_t child_pid;
    while (true) {
        int conn_fd = accept(listen_fd, reinterpret_cast<sockaddr*>(&cliaddr), &clilen);
        if (conn_fd == -1) {
            PrintErr();
            return -1;
        }
        if ((child_pid = fork()) == 0) {
            printf("rev conn req, start a child proc, pid=%u\n", child_pid);
            close(listen_fd);
            StrEcho(conn_fd);
            exit(0);
        }
        close(conn_fd);
    }

    return 0;
}

client.cpp代码

#include <arpa/inet.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

constexpr uint16_t SERV_PORT = 6666;
constexpr uint32_t MAXLEN = 4096;

inline void PrintErr()
{
    printf("errno = %s\n", strerror(errno));
}

int CreateSocket(const char *ip, uint16_t port, int& sock_fd)
{
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd == -1) {
        PrintErr();
        return -1;
    }

    sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(SERV_PORT);
    int ret = inet_pton(AF_INET, ip, &serv_addr.sin_addr);
    if (ret == -1) {
        printf("inet_pton err, argv[1]=%s\n", ip);
        return -1;
    }

    ret = connect(sock_fd, reinterpret_cast<sockaddr*>(&serv_addr), sizeof(serv_addr));
    if (ret == -1) {
        PrintErr();
        return -1;
    }

    return 0;
}

int main(int argc, char** argv)
{
    if (argc != 2) {
        exit(0);
    }

    int sock_fd;
    int ret = CreateSocket(argv[1], SERV_PORT, sock_fd);
    if (ret != 0) {
        exit(0);
    }

    char buf[MAXLEN];
    while (std::cin.getline(buf, MAXLEN)) {
        write(sock_fd, buf, strlen(buf));
        if (read(sock_fd, buf, MAXLEN) == 0) {
            exit(0);
        }
        printf("rev msg: %s\n", buf);
    }

    return 0;
}

makefile代码

all:server client
server:server.o
    g++ -g -o server server.o
client:client.o
    g++ -g -o client client.o
server.o:server.cpp
    g++ -g -c server.cpp
clinet.o:client.cpp
    g++ -g -c client.cpp
clean:all
    rm all

执行make命令,打开两个终端一个执行./server一个执行./client 127.0.0.1


TCP/IP网络编程,一个简单的TCP server


用TCP协议编写一个简单的服务器,客户端,服务器一直监听本机的6666端口。

server.cpp代码

#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

constexpr int MAXLNE = 4096;

int main(int argc, char **argv) 
{
    int listenfd, connfd, n;
    struct sockaddr_in servaddr;
    char buff[MAXLNE];

    if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(6666);

    if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
        printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    if (listen(listenfd, 10) == -1) {
        printf("listen socket error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    printf("========waiting for client's request========\n");
    while (true) {
        if ((connfd = accept(listenfd, (struct sockaddr *)nullptr, nullptr)) == -1) {
            printf("accept socket error: %s(errno: %d)\n", strerror(errno), errno);
            continue;
        }
        n = recv(connfd, buff, MAXLNE, 0);
        buff[n] = '\0';
        printf("recv msg from client: %s\n", buff);
        close(connfd);
    }

    close(listenfd);
    return 0;
}

client.cpp代码

#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

constexpr int MAXLNE = 4096;

int main(int argc, char **argv) 
{
    int sockfd, n;
    struct sockaddr_in servaddr;
    char sendline[MAXLNE], recvline[MAXLNE];

    if (argc != 2) {
        printf("usage: ./client <ipaddress>\n");
        return 0;
    }

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(6666);
    if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) {
        printf("inet_pton error for %s\n", argv[1]);
        return 0;
    }

    if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        printf("connect error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    printf("send msg to server: \n");
    fgets(sendline, MAXLNE, stdin);
    if (send(sockfd, sendline, strlen(sendline), 0) < 0) {
        printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    close(sockfd);
    return 0;
}

makefile代码

all:server client
server:server.o
    g++ -g -o server server.o
client:client.o
    g++ -g -o client client.o
server.o:server.cpp
    g++ -g -c server.cpp
clinet.o:client.cpp
    g++ -g -c client.cpp
clean:all
    rm all

执行make命令,打开两个终端一个执行./server一个执行./client 127.0.0.1