阻塞模式Echo服务器

/*
 * main.cc
 *
 *  Created on: 2009-11-30
 *      Author: liheyuan
 *    Describe: 阻塞模式服务器(Echo服务器)
 *
 *   Last Date: 2009-11-30
 *   CopyRight: 2009 @ ICT LiHeyuan
 */

#include <iostream>
using namespace std;

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define SERVER_PORT 18000

#define SERVER_QUEUE 10
#define MAX_BUF 16

int main() {

    //设置服务器Addr,在18000,任意IP监听
    int serverFd;
    serverFd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in serverAddr;
    socklen_t serverAddrLen = sizeof(sockaddr_in);
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serverAddr.sin_port = htons(SERVER_PORT);

    //绑定
    if (bind(serverFd, (sockaddr*) &serverAddr, serverAddrLen)) {
        cout << "Binding on " << SERVER_PORT << " fail." << endl;
        return -1;
    }

    //创建等待队列
    listen(serverFd, SERVER_QUEUE);

    //阻塞模式等待客户连接
    struct sockaddr_in clientAddr;
    int clientFd;
    socklen_t clientAddrLen;
    int len;
    char buf[MAX_BUF];
    while (1) {
        clientFd = accept(serverFd, (struct sockaddr*) &clientAddr,
                &clientAddrLen);
        cout << inet_ntoa(clientAddr.sin_addr) << " connect" << endl;
        while ((len = read(clientFd, buf, MAX_BUF)) > 0) {
            write(clientFd,buf,len);
        }
    }

    close(serverFd);
}
 

Leave a Reply

Your email address will not be published. Required fields are marked *