如何使用select从服务器向客户机发送数据 [英] How to Send data from server to clients using select

查看:158
本文介绍了如何使用select从服务器向客户机发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出了一些代码,帮助一些教程与客户端连接,并使用select函数接受来自slients的消息。现在我想做的是当服务器需要时将数据发送到特定的客户端。

 <$ c 

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

#define PORT9999//我们正在侦听的端口

//获取sockaddr,IPv4或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文件描述符列表
fd_set read_fds; // temp文件描述符列表()
fd_set write_fds;
int fdmax; //最大文件描述符数目

int listener; //侦听套接字描述符
int newfd; //新accept()ed套接字描述符
struct sockaddr_storage remoteaddr; //客户端地址
socklen_t addrlen;

char buf [256]; //缓冲区用于客户端数据
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); //清除主和临时集
FD_ZERO(& read_fds);
FD_ZERO(& write_fds);

//给我们一个套接字并绑定它
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\\\
,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;
}

//丢失讨厌的地址已被使用错误消息
setsockopt(listener,SOL_SOCKET,SO_REUSEADDR,& yes,sizeof(int));

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

break;
}

//如果我们到这里,这意味着我们没有绑定
if(p == NULL)
{
fprintf stderr,selectserver:failed to bind \\\
);
exit(2);
}

freeaddrinfo(ai) // all done with this

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

//将侦听器添加到主集合
FD_SET(listener,& master);

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

//跟踪最大的文件描述符
fdmax = listener; //到目前为止,这是一个
//接受3个客户端


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

//如果一些信号已经发生则写入连接
如果发生信号
{
向某些客户端发送数据;
}


//通过现有连接查找要读取的数据
//添加新连接读取连接
for(i = 0 ; i <= fdmax; i ++)
{

if(FD_ISSET(i,& read_fds))
{//我们有一个!
//处理新连接
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)
{//跟踪最大
fdmax = newfd;
}
printf(selectserver:来自%s在套接字%d \\\
上的新连接,inet_ntop(remoteaddr.ss_family,
get_in_addr((struct sockaddr *)& remoteaddr) remoteIP,INET6_ADDRSTRLEN),newfd);
}
} else
{
//从客户端处理数据
if((nbytes = recv(i,buf,sizeof buf,0) = 0)
{
//由客户端关闭的错误或连接
if(nbytes == 0)
{
//连接已关闭
printf (selectserver:socket%d hung up \\\
,i);
} else
{
perror(recv);
}
close(i); //再见!
FD_CLR(i,& master); //从主集中删除
} else
{
//从客户端获取一些数据
printf(Buffer we got%s,buf);

}
} // END从客户端处理数据
} // END有新的传入连接
memset(& buf [0],0,sizeof buf));
} // END循环通过文件描述符
} // END for(;;) - 你认为它永远不会结束!


return 0;

}

解决方案

您无法使用select();)将数据发送到客户端。



您可以



SUGGESTION:



查看Beej的指南 - 一个关于你感兴趣的套接字编程类型的精彩教程:





例如:

  char * msg =Beej在这里! 
int len,bytes_sent;



len = strlen(msg);
bytes_sent = send(sockfd,msg,len,0)


I came up with a code with help of some tutorials to connect with clients and accept messages from slients using the select function. Now I want to do is send data to a particular client when the server needed. How to accomplish this??.. Thanks in advance.

Server code

#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;

}

解决方案

You can't send data to a client using "select()" ;).

You can send data with a socket "send()", just as you're already reading data with "recv()".

SUGGESTION:

Check out Beej's Guide - an excellent primer on exactly the kind of socket programming you're interested in:

For example:

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

这篇关于如何使用select从服务器向客户机发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆