zoukankan      html  css  js  c++  java
  • win32 socket之select

    之前光看理论是不行滴,一定要实践,实践啊,不然永远都是门外汉!!

    嗯嗯,把找到的一段源码贴上先,稍微修改了一下:

    #include <winsock.h>
    #include <stdio.h>
    
    #include <string>
    
    #define PORT       5010
    #define MSGSIZE    1024
    int BytesSum = 0;
    
    #pragma comment(lib, "ws2_32.lib")
    
    DWORD WINAPI WorkerThread(LPVOID lpParameter);
    
    void InitWinSocket() 
    {
        WSADATA     wsaData;
        WSAStartup(0x0202, &wsaData);
    }
    
    #define ListenQ 10
    
    int main()
    {
        InitWinSocket();
    
        int opt = TRUE;
        int master_socket , addrlen , new_socket , client_socket[30] , max_clients = 30 , activity, i , valread , sd;
        int max_sd;
        struct sockaddr_in address;
    
        char buffer[1025];  //data buffer of 1K
    
        //set of socket descriptors
        fd_set readfds;
    
        //a message
        char *message = "ECHO Daemon v1.0 
    ";
    
        //initialise all client_socket[] to 0 so not checked
        for (i = 0; i < max_clients; i++) 
        {
            client_socket[i] = 0;
        }
    
        //create a master socket
        if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0) 
        {
            perror("socket failed");
            exit(EXIT_FAILURE);
        }
    
        //set master socket to allow multiple connections , this is just a good habit, it will work without this
        if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 )
        {
            perror("setsockopt");
            exit(EXIT_FAILURE);
        }
    
        //type of socket created
        address.sin_family = AF_INET;
        address.sin_addr.s_addr = INADDR_ANY;
        address.sin_port = htons( PORT );
    
        //bind the socket to localhost port 8888
        if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<0) 
        {
            perror("bind failed");
            exit(EXIT_FAILURE);
        }
        printf("Listener on port %d 
    ", PORT);
    
        //try to specify maximum of 3 pending connections for the master socket
        if (listen(master_socket, 3) < 0)
        {
            perror("listen");
            exit(EXIT_FAILURE);
        }
    
        //accept the incoming connection
        addrlen = sizeof(address);
        puts("Waiting for connections ...");
    
        while(TRUE) 
        {
            //clear the socket set
            FD_ZERO(&readfds);
    
            //add master socket to set
            FD_SET(master_socket, &readfds);
            max_sd = master_socket;
    
            //add child sockets to set
            for ( i = 0 ; i < max_clients ; i++) 
            {
                //socket descriptor
                sd = client_socket[i];
    
                //if valid socket descriptor then add to read list
                if(sd > 0)
                    FD_SET( sd , &readfds);
    
                //highest file descriptor number, need it for the select function
                if(sd > max_sd)
                    max_sd = sd;
            }
    
            //wait for an activity on one of the sockets , timeout is NULL , so wait indefinitely
            activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL);
    
            if (activity < 0) 
            {
                printf("select error");
            }
    
            //If something happened on the master socket , then its an incoming connection
            if (FD_ISSET(master_socket, &readfds)) 
            {
                if ((new_socket = accept(master_socket, (struct sockaddr *)&address,&addrlen))<0)
                {
                    perror("accept");
                    exit(EXIT_FAILURE);
                }
    
                //inform user of socket number - used in send and receive commands
                printf("New connection , socket fd is %d , ip is : %s , port : %d 
    " , new_socket , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
    
                //send new connection greeting message
                if( send(new_socket, message, strlen(message), 0) != strlen(message) ) 
                {
                    perror("send");
                }
    
                puts("Welcome message sent successfully");
    
                //add new socket to array of sockets
                for (i = 0; i < max_clients; i++) 
                {
                    //if position is empty
                    if( client_socket[i] == 0 )
                    {
                        client_socket[i] = new_socket;
                        printf("Adding to list of sockets as %d
    " , i);
    
                        break;
                    }
                }
            }
    
            //else its some IO operation on some other socket :)
            for (i = 0; i < max_clients; i++) 
            {
                sd = client_socket[i];
    
                if (FD_ISSET( sd , &readfds)) 
                {
                    //Check if it was for closing , and also read the incoming message
                    if ((valread = recv( sd , buffer, 1024,0)) == 0)
                    {
                        //Somebody disconnected , get his details and print
                        getpeername(sd , (struct sockaddr*)&address , &addrlen);
                        printf("Host disconnected , ip %s , port %d 
    " , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
    
                        //Close the socket and mark as 0 in list for reuse
                        closesocket( sd );
                        client_socket[i] = 0;
                    }
    
                    //Echo back the message that came in
                    else
                    {
                        //set the string terminating NULL byte on the end of the data read
                        buffer[valread] = '';
                        send(sd , buffer , strlen(buffer) , 0 );
                    }
                }
            }
        }
    
        return 0;
    }
    View Code

    ok,回家慢慢学习!

  • 相关阅读:
    94、二叉树的中序遍历 | JS
    102、二叉树的层序遍历 | JS
    111、二叉树的最小深度 | JS
    二叉树的先中后序遍历-JS非递归实现
    二叉树的先中后序遍历-JS递归实现
    深度和广度优先遍历-JS实现
    76、最小覆盖子串 | JS-字典
    extra1 二分查找与二叉判定树
    02 线性表的顺序存储
    原型、原型链、作用域、作用域链、闭包
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/3267620.html
Copyright © 2011-2022 走看看