如何构建TCP IP侦听器以使用chilkat套接字类c#读取传入消息

时间:2011-11-07 20:16:56

标签: c# .net sockets chilkat

我正在使用chilkat socket类。问题是我想保持我的套接字打开,让我说我执行了我的表单,并且第一次打开特定IP上的端口来监听消息。我能够第一次成功接收消息,现在在此之后消息我想让我的应用程序在收到新消息时继续收听和接收。

我们有几个客户端将在同一端口和ip上连接并发送一些短信。

但我无法做到这一点。我需要构建一个Listener,它将继续监听,一旦我得到任何消息,我需要处理它。任何使用过chilkat类或有此类应用经验的团体都建议我如何实现这一功能,因为我无法在CHILKAT网站上找到这种应用程序的好例子,或者可能是我没有经验但不知道如何准确编码这种类型的功能。

编辑1:杰米,

是的,我们已经开发了REST WCF服务并且它们工作正常,但问题是在REST WCF服务响应中出现了大响应标头,我们不希望这样,因为在我们的企业应用程序中Windows Phone 7移动设备也将沟通和发送短信只是为了移动设备,我们正在尝试减少我们需要传回的数据,并且通过使用套接字,我们可以避免额外的响应标头,而SMS因为成本而不是我们的选择。如果您对Webservices有任何建议,请尽量减少数据分享。

1 个答案:

答案 0 :(得分:0)

您是否考虑过Web服务?几乎任何可以发送Http请求的语言都可以使用它们。如果您可以控制客户端应用程序,那么Web服务肯定是正确的路径。

http://sarangasl.blogspot.com/2010/09/create-simple-web-service-in-visual.html

编辑:

您是否考虑过使用http响应代码进行简单的http上传字节。即Http Ok,Http Failure。您可以将状态代码自定义为适合您项目的任何内容。

编辑2:

也许RPC样式的方法只有http状态代码作为响应可能是合适的。检查此问题以获取提示。 json call with C#

基本上你只是将一些字符串发送到网址,然后再接收状态代码。这很小。

编辑3:

这是我用Reflector从一些旧代码中提取出来的东西。这只是程序的一般要点。显然第一次请求应该有一个using语句。

public void SMS(Uri address, string data)
{

   // Perhaps string data is JSON, or perhaps its something delimited who knows.
   // Json seems to be the pretty lean.
    try
    {
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(address);
        request.Method = "POST";
        // If we don't setup proxy information then IE has to resolve its current settings
        // and adds 500+ms to the request time.
        request.Proxy = new WebProxy();
        request.Proxy.IsBypassed(address);
        request.ContentType = "application/json;charset=utf-8";
        // If your only sending two bits of data why not add custom headers?
        // If you only send headers, no need for the StreamWriter.
        // request.Headers.Add("SMS-Sender","234234223");
        // request.Headers.Add("SMS-Body","Hey mom I'm keen for dinner tonight :D");
        request.Headers.Add("X-Requested-With", "XMLHttpRequest");
        StreamWriter writer = new StreamWriter(request.GetRequestStream());
        writer.WriteLine(data);
        writer.Close();
        using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                // Either read the stream or get the status code and description.
                // Perhaps you won't even bother reading the response stream or the code 
                // and assume success if no HTTP error status causes an exception.
            }
        }
    }
    catch (WebException exception)
    {
        if (exception.Status == WebExceptionStatus.ProtocolError)
        {
            // Something,perhaps a HTTP error is used for a failed SMS?
        }
    }
}

请记住仅响应Http状态代码和说明。并确保请求的代理设置为绕过请求的Url以节省解析IE代理的时间。