单个连接上有多个HttpWebRequests

时间:2015-05-08 23:35:57

标签: c# connection client httpwebrequest

所以我正在尝试为特定服务器编写客户端,模仿我在Chrome和Firefox等浏览器的开发工具中看到的行为。我正在使用HttpWebRequest,它似乎对我来说非常适合个人交换,但是一旦我需要使用另一个它就永远无法工作。我想我只需要存储我的ConnectionToken,以便服务器可以在多个请求中将我识别为同一个客户端,但事实并非如此。这是一个例子。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Web.Script.Serialization;


namespace WebClient
{
    class WebClientProgram
    {

        static void Main(string[] args)
        {
            //FIRST REQUEST, NEGOTIATE
            DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
            long epoch = (long)Math.Floor((DateTime.Now.ToUniversalTime() - unixStart).TotalSeconds);
            String timestamp = Convert.ToString(epoch);
            String uri = "http://domain/signalr/negotiate?_=" + timestamp;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            //Set REQUEST values
            request.Credentials = new NetworkCredential("username", "password");
            request.Method = "GET";
            request.KeepAlive = true;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            JavaScriptSerializer jSerialize = new JavaScriptSerializer();
            Dictionary<string, string> responseDictionary = jSerialize.Deserialize<Dictionary<string, string>>(reader.ReadToEnd());
            reader.Close();
            response.Close();
            String connectionToken = responseDictionary["ConnectionToken"];//Save my unique connection token
            String connectionID = responseDictionary["ConnectionId"];
            String protocolVersion = responseDictionary["ProtocolVersion"];

            //SECOND REQUEST, START
            epoch = (long)Math.Floor((DateTime.Now.ToUniversalTime() - unixStart).TotalSeconds);
            timestamp = Convert.ToString(epoch);
            uri = "http://domain/signalr/start?clientProtocol=" + protocolVersion + "&connectionToken=" + connectionToken + "&_=" + timestamp;
            request = (HttpWebRequest)WebRequest.Create(uri);
            //Set REQUEST values
            request.Credentials = new NetworkCredential("username", "password");
            request.Method = "GET";
            request.KeepAlive = true;

            response = (HttpWebResponse)request.GetResponse();//On this line I receive a 400 error from the server
            reader = new StreamReader(response.GetResponseStream());
            File.WriteAllText(@"start.txt", reader.ReadToEnd());
        }
    }
}

所以这就是我尝试为SignalR服务器进行基本交换,这正是我想要附加的内容。我首先NEGOTIATE并返回一个我用于以下请求的独特ConnectionToken。但是,以下请求始终会遇到响应“400:connection-id格式不正确”。 有什么想法吗?谢谢你们。

1 个答案:

答案 0 :(得分:0)

只是查看你的代码,你错过了url中的&符吗?

"&connectionToken=" + connectionToken + "此处 _=" + timestamp