区分使用插座之间的选择 [英] Differentiating Between Sockets using Select

查看:96
本文介绍了区分使用插座之间的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在侦听多端口的TCP / IP服务器。我选择使用选择启用多个事件的处理。

I'm making a TCP/IP server which listens on multiple ports. I chose to use select to enable handling of multiple events.

因此​​,在此刻,我有两个插座,分别连接到两个不同的端口(3000,3001)。

So at the moment, i have two sockets, which are connected to two different ports (3000, 3001).

在我的选择循环中,我希望服务器根据它目前正在处理端口上有不同的反应。我怎么能告诉我什么插座,一旦里面的选择?

Once I'm inside the select loop, I want the server to respond differently based on the port that it is currently handling. How can I tell what socket I'm on, once inside the select?

我添加了code为我选择的循环中,希望你们可以点我在正确的方向。请注意,这将启动我添加了两个文件描述符后套。

I'm adding the code for my selection loop, hopefully you guys can point me in the right direction. Notice that this starts after I've added both file descriptors to the set.

while(1)

{

    /* Block until input arrives on one or more active sockets. */

    readfds = activefds;

    if (select (FD_SETSIZE, &readfds, NULL, NULL, NULL) < 0)

    {

        perror ("select");

        exit (EXIT_FAILURE);

    }



    /* Service all the sockets with input pending. */

    for (i = 0; i < FD_SETSIZE; ++i)

    {

        if (FD_ISSET (i, &readfds))

        {

            if (i == S_time)

            {


                if ((NS = accept(S_time,NULL,NULL)) < 0)

                    ERROR("server: accept");

                FD_SET(NS, &activefds); //add the new socket desc to our active connections set

                send_time(NS);



            }

            else if (i == S_remote)// i == S_remote

            {

                fprintf(stderr,"Remote");

                int status = recieve_request(S_remote);

                /* Data arriving on an already-connected socket. */



            }

            else

            {

                break;

            }

        }

    } /* //end of for */

} /* //end of while */

所以我的两个插槽是S_TIME和S_remote。当客户端连接到插座时,我想给该客户端的当前时间。当客户端连接到远程,我想做远程执行。我怎样才能让这种区别?

So my two sockets are S_time and S_remote. When a client connects to the time socket, I want to send that client the current time. When a client connects to remote, I was want to do remote execution. How can i make this distinction?

感谢您的帮助。

推荐答案

选择()文件描述符交易,它不知道该端口号什么。

select() deals with file descriptors, it doesn't know anything about the port number.

您需要跟踪该信息自己(经由文件描述符键控地图,例如),或仅仅使用多组文件描述符(其中每组特定于一个端口)和呼叫选择在每个集零超时(非阻塞)。

You would need to keep track of this information yourself (via a map keyed by the file descriptor, for example) or simply use multiple sets of file descriptors (where each set is specific to a port) and call select with a zero timeout (non-blocking) on each set.

这篇关于区分使用插座之间的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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