• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Net.Connection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Associate

 internal void Associate(Connection connection)
 {
     lock (this.m_ConnectionList)
     {
         this.m_ConnectionList.Add(connection);
     }
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:7,代码来源:ConnectionGroup.cs


示例17: StreamManager

 public StreamManager (Connection serverConnection, TcpClient streamClient)
 {
     connection = serverConnection;
     updateThreadObject = new UpdateThread (this, streamClient);
     updateThread = new Thread (new ThreadStart (updateThreadObject.Main));
     updateThread.Start ();
 }
开发者ID:paperclip,项目名称:krpc,代码行数:7,代码来源:StreamManager.cs


示例18: RemoteDeploymentManager

        public RemoteDeploymentManager(string serviceUrl)
        {
            serviceUrl = UrlUtility.EnsureTrailingSlash(serviceUrl);
            _client = HttpClientHelper.Create(serviceUrl);

            // Raise the event when data comes in
            _connection = new Connection(serviceUrl + "status");
            _connection.Received += data => {
                if (StatusChanged != null) {
                    var result = JsonConvert.DeserializeObject<DeployResult>(data);
                    StatusChanged(result);
                }
            };

            _connection.Error += exception => {
                // If we get a 404 back stop listening for changes
                WebException webException = exception as WebException;
                if (webException != null) {
                    var webResponse = (HttpWebResponse)webException.Response;
                    if (webResponse != null &&
                        webResponse.StatusCode == HttpStatusCode.NotFound) {
                        _connection.Stop();
                    }
                }
            };

            _connection.Closed += () => {
                Debug.WriteLine("SignalR connection to {0} was closed.", serviceUrl);
            };

            _connection.Start().Wait();
        }
开发者ID:RaleighHokie,项目名称:kudu,代码行数:32,代码来源:RemoteDeploymentManager.cs


示例19: server_ClientConnceted

 static async void server_ClientConnceted(object sender, Connection con)
 {
     con.DataReceived += con_DataReceived;
     StringBuilder sb = new StringBuilder();
     var sampleData = File.ReadAllText(@"C:\PersonalProjects\TinyWebSocket\TinyWebSocket.Host\sample.txt", Encoding.UTF8);
     await con.Send(sampleData);
 }
开发者ID:nishant-chaturvedi,项目名称:TinyWebSocket,代码行数:7,代码来源:Program.cs


示例20: HandleAn400

        public void HandleAn400()
        {
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("errorMessage") };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var httpClient = Substitute.For<IHttpClient>();
            httpClient.SendAsync(Arg.Any<HttpRequestMessage>()).Returns(Task.FromResult(response));
            var connection = new Connection(httpClient, DotNetLoggerFactory.Create, "http://test.com");
            var generatedException = false;

            try
            {
                connection.Send<string>(HttpMethod.Get, "/thisIsATest").Wait();
            }
            catch (AggregateException e)
            {
                var aggregatedException = e.Flatten();
                Assert.AreEqual(1, aggregatedException.InnerExceptions.Count);
                var httpError = aggregatedException.InnerExceptions.FirstOrDefault();
                Assert.IsInstanceOf<HttpError>(httpError);
                // ReSharper disable once PossibleNullReferenceException
                Assert.AreEqual("Status Code : BadRequest, with content: errorMessage", httpError.Message);
                generatedException = true;
            }

            if (!generatedException)
            {
                Assert.Fail("Send should have thrown an HttpError exception");
            }
        }
开发者ID:JudoPay,项目名称:DotNetSDK,代码行数:29,代码来源:ConnectionTests.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Net.Cookie类代码示例发布时间:2022-05-26
下一篇:
C# Net.BufferOffsetSize类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap