【问题标题】:How to Send data from server to clients using select如何使用 select 将数据从服务器发送到客户端
【发布时间】:2012-12-31 14:38:24
【问题描述】:

我在一些教程的帮助下想出了一个代码,用于连接客户端并使用 select 函数接受来自 slients 的消息。现在我想做的是在服务器需要时将数据发送到特定的客户端。如何做到这一点??..提前致谢。

服务器代码

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

#define PORT "9999"   // 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)
{
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 500000;

fd_set master;    // master file descriptor list
fd_set read_fds;  // temp file descriptor list for select()
fd_set write_fds;
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);
FD_ZERO(&write_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);

printf("Listener is %d \n" , listener);

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


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

    //WRITE TO CONNECTIONS IF SOME SIGNAL OCCURED
    if(signal occured)
    {
        send data to some client;
    }


    // run through the existing connections looking for data to read
    // ADD NEW CONNECTIONS READ FROM CONNECTIONS
    for(i = 0; i <= fdmax; i++) 
    {

        if (FD_ISSET(i, &read_fds)) 
        { // we got one!!
            // handle new connections
            if (i == listener) 
            {                    

                addrlen = sizeof(remoteaddr);
                newfd = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen);
                //write(listener+1 , "SERVER MESSAGE :: ACCEPTED" ,26);
                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 
                {
                    // we got some data from a client
                    printf("Buffer we got %s ",buf);

                }
            } // END handle data from client
        } // END got new incoming connection
        memset(&buf[0], 0, sizeof(buf));
    } // END looping through file descriptors
} // END for(;;)--and you thought it would never end!


return 0;

}

【问题讨论】:

    标签: c++ sockets network-programming client-server


    【解决方案1】:

    您不能使用“select()”向客户端发送数据;)。

    可以使用套接字“send()”发送数据,就像您已经使用“recv()”读取数据一样。

    建议:

    查看 Beej 指南 - 关于您感兴趣的套接字编程类型的优秀入门:

    例如:

    char *msg = "Beej was here!";
    int len, bytes_sent;
    .
    .
    .
    len = strlen(msg);
    bytes_sent = send(sockfd, msg, len, 0)
    

    【讨论】:

    • 啊,这意味着我可以使用 select 功能识别可用的 fd 并使用 send 为它们发送数据...感谢您的回答和教程。 :)
    • 是的,这正是“select()”的用途。找出哪些(可能有很多)输入提供了 I/O。
    • FD_ISSET(FD , &read_fd) 真正返回什么??.. 是否说明 FD 可用??..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2021-12-07
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多