| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 5402 人关注过本帖
标题:聊天服务器 selectServer.c
取消只看楼主 加入收藏
madfrogme
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:21
帖 子:1160
专家分:1106
注 册:2009-6-24
结帖率:98.63%
收藏
 问题点数:0 回复次数:0 
聊天服务器 selectServer.c
程序代码:
/*
  * selectserver.c -- 多人聊天服务器,可以通过 $ telnet 192.168.1.102 9034 来连接到服务器
  */

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

#define PORT "9034"   // port we're listening on

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET) 

        return &(((struct sockaddr_in*)sa)->sin_addr);


    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

int main(void)
{
    fd_set master;    // master file descriptor list

    fd_set read_fds;  // temp file descriptor list for select()

    int fdmax;        // maximum file descriptor number

    int listener;     // listening socket descriptor

    int newfd;        // newly accept()ed socket descriptor

    struct sockaddr_storage remoteaddr; // client address

    socklen_t addrlen;

    char buf[256];    // buffer for client data

    int nbytes;

    char remoteIP[INET6_ADDRSTRLEN];

    int yes=1;        // for setsockopt() SO_REUSEADDR, below

    int i, j, rv;

    struct addrinfo hints, *ai, *p;

    FD_ZERO(&master);    // clear the master and temp sets

    FD_ZERO(&read_fds);

    // get us a socket and bind it
    memset(&hints, 0, sizeof hints);

    hints.ai_family = AF_UNSPEC;

    hints.ai_socktype = SOCK_STREAM;

    hints.ai_flags = AI_PASSIVE;

    if ((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0) {

        fprintf(stderr, "selectserver: %s\n", gai_strerror(rv));

        exit(1);
}

    for(p = ai; p != NULL; p = p->ai_next) {

        listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);

        if (listener < 0) 

            continue;


        // lose the pesky "address already in use" error message
        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

        if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) {
            close(listener);
            continue;
        }

        break;
    }

    // if we got here, it means we didn't get bound
    if (p == NULL) {
        fprintf(stderr, "selectserver: failed to bind\n");

        exit(2);
    }

    freeaddrinfo(ai); // all done with this

    // listen
    if (listen(listener, 10) == -1) {
        perror("listen");
        exit(3);
    }

    // add the listener to the master set
    FD_SET(listener, &master);

    // keep track of the biggest file descriptor
    fdmax = listener; // so far, it's this one

    // main loop
    for(;;) {
        read_fds = master; // copy it
        if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
            perror("select");
            exit(4);
        }

        /* run through the existing connections looking for data to read*/
        /*每增加一个新客户,fdmax都会增加1*/
        for(i = 0; i <= fdmax; i++) {
            
            /*可以在下面添加一个printf() 用来观察i 的变化*/
         // printf("%d",i )
            if (FD_ISSET(i, &read_fds)) { // we got one!!

                /* either listen on socket or recvive data from client 
                 * 这里的 listener 可能一直为4
                 * newfd 则是5,6,7的变化
                 */
                if (i == listener) {

                    // handle new connections
                    addrlen = sizeof remoteaddr;

                    /* always use the minimum numbber*/
                    newfd = accept(listener,(struct sockaddr *)&remoteaddr,&addrlen);

                    if (newfd == -1)

                        perror("accept");

                    else {

                        FD_SET(newfd, &master); // add to master set

                        if (newfd > fdmax)    // keep track of the max

                            fdmax = newfd;

                        printf("selectserver: new connection from %s on socket %d\n",inet_ntop(remoteaddr.ss_family,get_in_addr((struct sockaddr*)&remoteaddr),remoteIP, INET6_ADDRSTRLEN),
                            newfd);
                    }
                }
                else {
                    // handle data from a client
                    if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {

                        // got error or connection closed by client
                        if (nbytes == 0)

                            // connection closed
                            printf("selectserver: socket %d hung up\n", i);

                        else 
                            perror("recv");

                        close(i); // bye!

                        FD_CLR(i, &master); // remove from master set
                    } else

                        // 从client 那儿得到数据了
                        for(j = 0; j <= fdmax; j++)

                            // 发送给所有人
                            if (FD_ISSET(j, &master))

                                // 除了listener 和我们自己不发送
                                if (j != listener && j != i) 

                                    if (send(j, buf, nbytes, 0) == -1) 
                                        perror("send");

                } 
            } 
        } 
    } 
    return 0;
}


[ 本帖最后由 madfrogme 于 2012-8-31 15:22 编辑 ]
搜索更多相关主题的帖子: return include listening 聊天 服务器 
2012-08-31 14:21
快速回复:聊天服务器 selectServer.c
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.030060 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved