当前位置: 首页>>代码示例>>C#>>正文


C# Net.Connection类代码示例

本文整理汇总了C#中System.Net.Connection的典型用法代码示例。如果您正苦于以下问题:C# Connection类的具体用法?C# Connection怎么用?C# Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Connection类属于System.Net命名空间,在下文中一共展示了Connection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OpenConnection

        private void OpenConnection(Connection connection, string data, Action initializeCallback, Action<Exception> errorCallback)
        {
            var url = connection.Url + GetReceiveQueryString(connection, data);

            Action<HttpWebRequest> prepareRequest = PrepareRequest(connection);

            HttpHelper.GetAsync(url, request =>
            {
                prepareRequest(request);

                request.Accept = "text/event-stream";

                if (connection.MessageId != null)
                {
                    request.Headers["Last-Event-ID"] = connection.MessageId.ToString();
                }

            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    errorCallback(task.Exception);
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    var stream = task.Result.GetResponseStream();
                    var reader = new AsyncStreamReader(stream, connection, initializeCallback, errorCallback);
                    reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[ReaderKey] = reader;
                }
            });
        }
开发者ID:codeinpeace,项目名称:SignalR,代码行数:35,代码来源:ServerSentEventsTransport.cs

示例2: SendIssueReportAsync

        public async Task SendIssueReportAsync(IssueReport report)
        {
            var appId = _propertyProvider.GetProperty("locco.github.appId");
            var accessToken = _propertyProvider.GetProperty("locco.github.token");
            var repoOwner = _propertyProvider.GetProperty("locco.github.owner");
            var repoName = _propertyProvider.GetProperty("locco.github.repository");

            // Support default proxy
            var proxy = WebRequest.DefaultWebProxy;
            var httpClient = new HttpClientAdapter(() => HttpMessageHandlerFactory.CreateDefault(proxy));
            var connection = new Connection(new ProductHeaderValue(appId), httpClient);

            if (proxy != null)
            {
                Log.Info(string.Format("Using proxy server '{0}' to connect to github!", proxy.GetProxy(new Uri("https://api.github.com/"))));
            }


            var client = new GitHubClient(connection)
            {
                Credentials = new Credentials(accessToken)
            };


            // Creates a new GitHub Issue
            var newIssue = new NewIssue(report.Title)
            {
                Body = MarkdownReportUtil.CompileBodyMarkdown(report, 220000),
            };
            newIssue.Labels.Add("bot");

            var issue = await client.Issue.Create(repoOwner, repoName, newIssue);
        }
开发者ID:ElderByte-,项目名称:Archimedes.Locco,代码行数:33,代码来源:GitHubProvider.cs

示例3: HandleSessionAsynchronously

        /// <summary>
        /// When session has completed, log any error which occured and dispose resources. This is done asynchronously
        /// sincew we want to be able to start new session without previous to complete.
        /// </summary>
        private void HandleSessionAsynchronously(Task sessionTask, Connection connection, ISession session)
        {
            sessionTask.ContinueWith(f =>
            {
                if (f.IsFaulted)
                {
                    var exception = f.Exception.InnerException;

                    _log.LogException(new LogEvent()
                    {
                        LogLevel = LogLevel.Error,
                        EventType = LogEventType.Application,
                        Message = exception.Message,
                        RemoteEndpoint = connection.RemoteEndpoint,
                        SessionId = connection.SessionId,
                        Protocol = session.Protocol.ToString()
                    }, exception);
                }

                SessionManager.DecreaseSessionCount(session.Protocol);

                // Session has ended.
                connection.Dispose();
            });
       }
开发者ID:hmailserver,项目名称:hmailserver-net,代码行数:29,代码来源:Server.cs

示例4: Timeout

 public void Timeout()
 {
     // Had to pick a routable IP, but one that won't return packets... don't know of a better choice than this
     var connection = new Connection(new IPEndPoint(IPAddress.Parse("10.230.220.210"), 28015));
     connection.ConnectTimeout = TimeSpan.FromSeconds(1);
     connection.Connect();
 }
开发者ID:jrote1,项目名称:rethinkdb-net,代码行数:7,代码来源:ConnectTests.cs

示例5: AddToConnectionList

        // Receive incoming initial Connection messages from Clients...
        public static void AddToConnectionList(PacketHeader header, Connection connection, string Connection)
        {
            // Add incoming IP Address to HashSet list...
            ConnectionsList.Add(connection.ConnectionInfo.RemoteEndPoint.Address.ToString() + "|" + Connection);

            // Respond to sender that they are succesfully connected.
            connection.SendObject("Connected", "CONNECTED!");
            Console.WriteLine("\n" + connection.ConnectionInfo.RemoteEndPoint.Address.ToString() + " has CONNECTED!");

            // Send all active connections to all active connections for Client List.
            foreach (var item in NetworkComms.GetExistingConnection())
            {
                foreach (var items in ConnectionsList.Distinct())
                {
                    item.SendObject("Connection", items);
                }
            }

            /* Old method to create files on hard disk for testing the code...
               if (!File.Exists(ConnectionFilePath))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(ConnectionFilePath))
                {
                }
            }
            using (StreamWriter sw = File.AppendText(ConnectionFilePath))
            {
                sw.WriteLine(connection.ConnectionInfo.RemoteEndPoint.Address.ToString());
            } */
        }
开发者ID:Kriosym,项目名称:JungleTimers,代码行数:32,代码来源:Program.cs

示例6: RunAsync

        public async Task RunAsync()
        {
            _listener.Start();

            while (true)
            {
                TcpClient tcpClient = null;

                try
                {
                    tcpClient = await _listener.AcceptTcpClientAsync();
                }
                catch (ObjectDisposedException)
                {
                    // When TcpListener is stopped, outstanding calls to AcceptTcpClientAsync
                    // will throw an ObjectDisposedException. When this happens, it's time to 
                    // exit.
                    return;
                }


                var connection = new Connection(tcpClient, _cancellationTokenSource.Token);

                var session = _sessionFactory();

                var sessionTask = session.HandleConnection(connection);

                SessionManager.IncreaseSessionCount(session.Protocol);

                HandleSessionAsynchronously(sessionTask, connection, session);
            }
        }
开发者ID:hmailserver,项目名称:hmailserver-net,代码行数:32,代码来源:Server.cs

示例7: RtspTunnel

		public RtspTunnel(int rtspPort, int imagePort, Connection<MonoBrick.EV3.Command,MonoBrick.EV3.Reply> ev3Connection){
			Running = false;
			RTSPPort = rtspPort;
			this.nxtConnection = null;
			this.ev3Connection = ev3Connection;
			this.hostImagePort = imagePort;
		}
开发者ID:seipekm,项目名称:MonoBrick-Communication-Software,代码行数:7,代码来源:Tunnel.cs

示例8: SetUp

 public void SetUp()
 {
     ConnectionArgs args = new ConnectionArgs("deltabot","irc.sventech.com");
     connection = new Connection( args );
     RegisterListeners();
     AssignLines();
 }
开发者ID:Iciclebar,项目名称:ThreshIRC,代码行数:7,代码来源:DccListenerTest.cs

示例9: HandleHttpRequest

		protected override void HandleHttpRequest(Connection connection, HttpServerRequest request, HttpServerResponse response)
		{
			base.HandleHttpRequest(connection, request, response);

			if (response.ContentSource != ContentSource.ContentNone)
			{
				return;
			}

			if (request.Header.RequestType != "GET")
			{
				response.SendError(HttpStatusCode.BadRequest, String.Format("Request Type '{0}' not supported.", request.Header.RequestType));
				return;
			}

			String lPath = RootPath + request.Header.RequestPath.Replace('/', Path.DirectorySeparatorChar);
			if (lPath.IndexOf("..", StringComparison.Ordinal) != -1)
			{
				response.SendError(HttpStatusCode.Forbidden, String.Format("Bad Request: Path '{0}' contains '..' which is invalid.", lPath));
				return;
			}

			if (!File.Exists(lPath))
			{
				response.SendError(HttpStatusCode.NotFound, String.Format("File '{0}' not found.", lPath));
				return;
			}

			response.Header.ContentType = "text/html";
			response.ContentStream = new FileStream(lPath, FileMode.Open, FileAccess.Read, FileShare.Read);
			response.CloseStream = true; /* Response will close stream once it's been sent */
		}
开发者ID:remobjects,项目名称:internetpack,代码行数:32,代码来源:SimpleHttpServer.cs

示例10: GlobalChatBot

        public GlobalChatBot(string nick)
        {
            /*if (!File.Exists("Sharkbite.Thresher.dll"))
            {
                Server.UseGlobalChat = false;
                Server.s.Log("[GlobalChat] The IRC dll was not found!");
                return;
            }*/
            server = "irc.geekshed.net";
            channel = "#MCForge";
            this.nick = nick.Replace(" ", "");
            connection = new Connection(new ConnectionArgs(nick, server), false, false);

            if (Server.UseGlobalChat)
            {
                // Regster events for incoming
                connection.Listener.OnNickError += new NickErrorEventHandler(Listener_OnNickError);
                connection.Listener.OnRegistered += new RegisteredEventHandler(Listener_OnRegistered);
                connection.Listener.OnPublic += new PublicMessageEventHandler(Listener_OnPublic);
                connection.Listener.OnJoin += new JoinEventHandler(Listener_OnJoin);
                connection.Listener.OnKick += new KickEventHandler(Listener_OnKick);
                connection.Listener.OnError += new ErrorMessageEventHandler(Listener_OnError);
                connection.Listener.OnDisconnected += new DisconnectedEventHandler(Listener_OnDisconnected);
            }
        }
开发者ID:Goodlyay,项目名称:MCForge-Vanilla-Redux,代码行数:25,代码来源:GlobalChatBot.cs

示例11: Register

        public User Register([FromBody] User user)
        {
            _conn = new Connection(_connectionString);
            _conn.OpenConnection();

            //Calculate MD5 hash
            MD5 md5 = MD5.Create();
            byte[] inputBytes = Encoding.ASCII.GetBytes(user.Username + user.PasswordHash + DateTime.Now);
            byte[] hash = md5.ComputeHash(inputBytes);
            StringBuilder tokenString = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                tokenString.Append(hash[i].ToString("X2"));
            }

            bool result = _conn.Register(user.Username, user.PasswordHash, tokenString.ToString());
            _conn.CloseConnection();
            if (result)
            {
                user.Token = tokenString.ToString();
                return user;
            }
            else
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict));
            }
        }
开发者ID:rinojk,项目名称:ZipDoc,代码行数:27,代码来源:UserController.cs

示例12: Get

        public IConnection Get(string clusterName)
        {
            if (DefaultSettings.Value == null)
                throw new ConfigurationErrorsException("No rethinkdb client configuration section located");

            foreach (ClusterElement cluster in DefaultSettings.Value.Clusters)
            {
                if (cluster.Name == clusterName)
                {
                    List<EndPoint> endpoints = new List<EndPoint>();
                    foreach (EndPointElement ep in cluster.EndPoints)
                    {
                        IPAddress ip;
                        if (IPAddress.TryParse(ep.Address, out ip))
                            endpoints.Add(new IPEndPoint(ip, ep.Port));
                        else
                            endpoints.Add(new DnsEndPoint(ep.Address, ep.Port));
                    }

                    var connection = new Connection(endpoints.ToArray());
                    if (!String.IsNullOrEmpty(cluster.AuthorizationKey))
                        connection.AuthorizationKey = cluster.AuthorizationKey;
                    return connection;
                }
            }

            throw new ArgumentException("Cluster name could not be found in configuration", "clusterName");
        }
开发者ID:jchannon,项目名称:rethinkdb-net,代码行数:28,代码来源:ConfigConnectionFactory.cs

示例13: Update_Should_Update_A_Connection

 public void Update_Should_Update_A_Connection() 
 {
     _repository
          .Setup(it => it.Update(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<Boolean>(), It.IsAny<Int32>()))
          .Callback<String, String, Boolean, Int32>((name, connectionString, isActive, connectionId) => 
     { 
          var tConnection = _repositoryList.Find(x => x.ConnectionId==connectionId);
          tConnection.Name = name; 
          tConnection.ConnectionString = connectionString; 
          tConnection.IsActive = isActive; 
     });
     var tempConnection = _repositoryList.Find(x => x.ConnectionId==connectionId);
     var testConnection = new Connection {
          ConnectionId = tempConnection.ConnectionId, 
          Name = tempConnection.Name, 
          ConnectionString = tempConnection.ConnectionString, 
          IsActive = tempConnection.IsActive};
     
     //TODO change something on testConnection
     //testConnection.oldValue = newValue; 
     _target.Update(testConnection);
     //Assert.AreEqual(newValue, _repositoryList.Find(x => x.ConnectionId==1).oldValue);
     //TODO fail until we update the test above
     Assert.Fail();
 }
开发者ID:leloulight,项目名称:LucentDb,代码行数:25,代码来源:ConnectionWebAPITest.cs

示例14: InitializeClientHandshake

        protected override void InitializeClientHandshake(NetContext context, Connection conn)
        {
            var connection = (WebSocketConnection) conn;
            if (string.IsNullOrEmpty(connection.Host)) throw new InvalidOperationException("Host must be specified");
            if (string.IsNullOrEmpty(connection.RequestLine)) throw new InvalidOperationException("RequestLine must be specified");

            string key1 = CreateRandomKey(), key2 = CreateRandomKey();
            byte[] key3 = new byte[8];
            NetContext.GetRandomBytes(key3);

            StringBuilder req = new StringBuilder(connection.RequestLine).Append("\r\n" +
                                    "Upgrade: WebSocket\r\n" + // note casing!
                                    "Connection: Upgrade\r\n" +
                                    "Sec-WebSocket-Key1: ").Append(key1).Append("\r\n" +
                                    "Sec-WebSocket-Key2: ").Append(key2).Append("\r\n" +
                                    "Host: ").Append(connection.Host).Append("\r\n");
            if (!string.IsNullOrEmpty(connection.Origin))
                req.Append("Origin: ").Append(connection.Origin).Append("\r\n");
            if (!string.IsNullOrEmpty(connection.Protocol))
                req.Append("Sec-WebSocket-Protocol: ").Append(connection.Protocol).Append("\r\n");
            req.Append("\r\n");




            expectedSecurityResponse = WebSocketsProcessor_Hixie76_00.ComputeKey(key1, key2, key3);
            EnqueueFrame(context, new StringFrame(req.ToString(), Encoding.ASCII, false));
            EnqueueFrame(context, new BinaryFrame(key3));
            connection.PromptToSend(context);
        }
开发者ID:mpotra,项目名称:NetGain,代码行数:30,代码来源:WebSocketsClientProcessor.cs

示例15: OnAsyncAccepted

        public void OnAsyncAccepted(IAsyncResult result)
        {
            Socket nsock = _listener.EndAccept(result);

            lock (_free_connections)
            {
                // Occupy new slot.
                int pos = _free_connections.Count - 1;
                if (pos >= 0)
                {
                    int connection_id = _free_connections[pos];
                    _free_connections.RemoveAt(pos);

                    Connection c = new Connection();
                    c.socket = nsock;
                    c.recvbuf = new byte[4096];
                    c.conn = _handler.OnConnected(connection_id, c);
                    _connections[connection_id] = c;

                    nsock.BeginReceive(c.recvbuf, 0, c.recvbuf.Length, 0, OnAsyncReceive, connection_id);
                }
                else
                {
                    Console.WriteLine("Dropping connection because i am full");
                    nsock.Close();
                }
            }

            _listener.BeginAccept(OnAsyncAccepted, _listener);
        }
开发者ID:raxptor,项目名称:putki-historical,代码行数:30,代码来源:PacketStreamServer.cs


注:本文中的System.Net.Connection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。