0

我正在尝试编写一个自定义的基于 TCP 的长轮询服务器,它将作为其他 TCP 连接的中间人,这些连接需要比手机提供更多的持久性。

我尝试这样做的方法是用 C# 编写一个异步 TCP 服务器和一个同样用 C# 编写的匹配 TCP 客户端。

长轮询的工作方式(据我所知)是您打开到服务器的 TCP 连接,并且服务器在通过套接字发送回数据之前停止。您发现在移动电话网络上有效的心跳间隔(我听说大约 8 分钟有效?)如果没有更新数据,您将发送一个空数据包。

这就是我的麻烦所在。我不知道如何将客户端的数据请求与服务器上运行的事件处理程序“链接”起来……

流程应该是这样的(“客户端”在电话上):

  1. 用户启动我的应用程序

  2. 客户端发送请求以在数据发生更改时得到通知

  3. 服务器“链接”(注册)客户端的套接字对象到一个“事件处理程序”中,由服务器的其他 TCP 连接调用,我谈到了!

  4. 事件

    o 如果被触发(新数据到了),将数据发送给客户端

    o 如果没有触发(没有新数据),向客户端发送一个“EmptyChanges”数据包

  5. 客户端在手机上接收数据并对其进行处理(根据接收到的数据包类型调用事件处理程序,并将从服务器获得的“数据”传递给它)

  6. 客户端发送请求以在数据发生更改时得到通知

所以,我的问题是我想不出一个能完成我想要它做的设计。问题是我不知道如何做#3。如何“链接”一个事件处理程序与另一个事件处理程序?这些几乎可以保证在不同的线程上运行!

所以,我的应用程序看起来像这样(所有伪代码):

Class AppClass
{
    Main()

    List<Client> clients;
    List<DataServers> dataServers;

    DataReceivedFromServer(Data stuff)
    {
    }

    MessageReceivedFromPhone(PhoneMessage pm, object sender)
    {
        //Loop here until HeartBeat interval reached
        Int totalTime = 0;
        While(totalTime < HEARTBEAT_INTERVAL)
        {
            If( ) // If we have received data from the server, and the client WANTED that data, send it now
            {
            }
        }
    }
}

有点儿?我希望它是事件驱动的,但我正忙着弄清楚如何以 PUSH 驱动风格驱动应用程序与我“习惯”的轮询方式。

请善待,因为我可能会做一些过于复杂和愚蠢的事情,因为这是我第一次真正尝试使用 Socket 编程(从不需要它),而且由于手机在瞬态网络上的性质以及我的服务器需要使用 OPEN TCP 连接维护这些电话的位置。

服务器平台:Windows

服务器语言:C#

测试客户端平台:Windows

测试客户端语言:C#

目标客户端平台:Windows Mobile 6.5、iPhone、Android(客户端另写)

目标客户端语言:C#、Obj-C 或 MonoTouch、Java

4

1 回答 1

0

Just anyone wondering this, I trashed the idea of writing a custom TCP server to manage my connections. There was so much overhead in doing that, I'd basically be replicating writing my own HTTP server, so instead of doing that, I went with the Web Tornado framework in Python as my server and am writing the back end services to communicate through HTTP requests in Web Tornado.

Instead of using Long polling at all, I'm going to use SMS for push notifications. I believe all of the major phone platforms implement something similar to an SMS Interceptor that you write... if an SMS of a certain format comes through, it will run your custom code. This allows me to remove the requirements of using consistent open connections (other than for live chat, which will use a comet style Long poll, but the connection can only remain open if active for about 5 minutes.)

Basically, the Web Tornado framework is serving as an Enterprise bus in my architecture.

于 2009-11-25T04:02:43.137 回答