[Linux Programming] Echo(Simple Demo)

综合前面的 "文件操作" "线程" "套接字", 可以写一个简单的echo服务了.

// client
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // sockaddr_in
#include <arpa/inet.h> // inet_pton
#include <unistd.h> // close
#include <string.h> // bzero

#include <iostream>
#include <string>

using namespace std;

const unsigned int SERVER_PORT = 1234;
const char* SERVER_IP = "127.0.0.1"; // or your host address

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

    sockaddr_in svr_addr;
    bzero(&svr_addr, sizeof(sockaddr_in));
    svr_addr.sin_family = AF_INET;
    svr_addr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP, &svr_addr.sin_addr);
    connect(sockfd, (sockaddr*)&svr_addr, sizeof(svr_addr));

    while(1) {
        char buf[20];
        size_t n = read(1, buf, 20); // read from std input
        if(n > 0) {
            if(n == 2 && buf[0] == 'q') break; // "q\n"
            else write(sockfd, buf, n); // write socket
        }
    }

    close(sockfd);

    return 0;
}
// server
#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <unistd.h>
#include <string.h>

#include <pthread.h>

#include <iostream>
using namespace std;

const unsigned int SERVER_PORT = 1234;
const unsigned int LISTEN_QUEUE_LENTH = 5;

void *echo_thread(void *);

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

    sockaddr_in svr_addr;
    bzero(&svr_addr, sizeof(sockaddr_in));
    svr_addr.sin_family = AF_INET;
    svr_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    svr_addr.sin_port = htons(SERVER_PORT);
    socklen_t addr_len = sizeof(sockaddr);
    bind(lfd, (sockaddr*)&svr_addr, addr_len);

    listen(lfd, LISTEN_QUEUE_LENTH);

    sockaddr_in clt_addr;
    while (1) {
        int cfd = accept(lfd, (sockaddr*)&clt_addr, &addr_len);
        if (cfd > 0) {
            pthread_t tid;
            pthread_create(&tid, NULL, echo_thread, &cfd);
        }
    }

    return 0;
}

void* echo_thread(void* fd) {
    int sockfd = *((int*)fd);
    while(1) {
        char buf[20];
        size_t n = read(sockfd, buf, 20); // read from socket
        if(n == 0) break; // client close
        else if(n > 0) write(2, buf, n); // write to std output
    }

    cout << "thread return, close connection." << endl;
    close(sockfd);

    return NULL;
}

发表评论

电子邮件地址不会被公开。必填项已用 * 标注