void EnsureSocket2() { if (_Socket2 == null) { var socket = Socket.Client; var ep = socket.LocalEndPoint as IPEndPoint; var sto = socket.SendTimeout; var rto = socket.ReceiveTimeout; // 如果原端口没有启用地址重用,则关闭它 var value = socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress); if (!Convert.ToBoolean(value)) { socket.Close(); } //var sk = NetService.Container.Resolve<ISocketClient>(socket.ProtocolType); ////sk.Address = ep.Address; ////sk.Port = ep.Port; //sk.Local.EndPoint = ep; var sk = new NetUri((NetType)socket.ProtocolType, ep).CreateClient(); sk.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //sk.Bind(); sk.Client.SendTimeout = sto; sk.Client.ReceiveTimeout = rto; _Socket2 = sk; } }
/// <summary>创建客户端会话</summary> /// <param name="uri"></param> /// <returns></returns> protected virtual HttpSession Create(NetUri uri) { var http = uri.CreateRemote() as HttpSession; http.Log = Log; //if (XTrace.Debug) //{ // http.LogSend = true; // http.LogReceive = true; //} http.UserAgent = UserAgent; if (AutomaticDecompression != DecompressionMethods.None) { http.Compressed = true; } if (!String.IsNullOrEmpty(Accept)) { http.Headers[HttpRequestHeader.Accept] = Accept; } if (!String.IsNullOrEmpty(AcceptLanguage)) { http.Headers[HttpRequestHeader.AcceptLanguage] = AcceptLanguage; } if (!String.IsNullOrEmpty(Referer)) { http.Headers[HttpRequestHeader.Referer] = Referer; } return(http); }
private void btnSend_Click(Object sender, EventArgs e) { if (_Client == null || !_Client.Active) { return; } var count = (Int32)numThreads.Value; if (count <= cs.Count) { return; } //var sc = _Client.Client.GetService<ISocketClient>(); //if (sc == null) return; var uri = new NetUri(cbAddr.Text); Task.Run(() => { var cc = _Client; for (var i = 0; i < count; i++) { var ac = new LinkClient(uri.ToString()) { //ac.Received += OnReceived; UserName = cc.UserName, Password = cc.Password, ActionPrefix = cc.ActionPrefix }; //ac.Encrypted = cc.Encrypted; //ac.Compressed = cc.Compressed; cs.Add(ac); Task.Run(() => { for (var k = 0; k < 10; k++) { if (ac.Open()) { break; } Thread.Sleep(1000); } //// 共用统计对象 //if (ac.Active) //{ // var sc2 = ac.Client.GetService<ISocketClient>(); // sc2.StatSend = sc.StatSend; // sc2.StatReceive = sc.StatReceive; //} }); } }); }
protected override RedisClient OnCreate() { var node = Node; var rds = node.Owner; var addr = node.EndPoint; if (addr.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(node.EndPoint)); } var uri = new NetUri("tcp://" + addr); if (uri.Port == 0) { uri.Port = 6379; } var rc = new RedisClient { Server = uri, Password = rds.Password, }; rc.Log = rds.Log; if (rds.Db > 0) { rc.Select(rds.Db); } return(rc); }
/// <summary>启动</summary> public override void Start() { var cfg = Config; var ss = cfg.NameServerAddress.Split(";"); //Servers = ss.Select(e => new NetUri(e)).ToArray(); var list = new List <NetUri>(); foreach (var item in ss) { var uri = new NetUri(item); if (uri.Type == NetType.Unknown) { uri.Type = NetType.Tcp; } list.Add(uri); } Servers = list.ToArray(); base.Start(); if (_timer == null) { _timer = new TimerX(DoWork, null, cfg.PollNameServerInterval, cfg.PollNameServerInterval); } }
static void Test6() { // UDP没有客户端服务器之分。推荐使用NetUri指定服务器地址 var udp = new UdpServer(); udp.Remote = new NetUri("udp://smart.peacemoon.cn:7"); udp.Received += (s, e) => { XTrace.WriteLine("收到:{0}", e.ToStr()); }; udp.Open(); udp.Send("新生命团队"); udp.Send("学无先后达者为师!"); // Tcp客户端会话。改用传统方式指定服务器地址 var tcp = new TcpSession(); tcp.Remote.Host = "smart.peacemoon.cn"; tcp.Remote.Port = 13; tcp.Open(); var str = tcp.ReceiveString(); XTrace.WriteLine(str); // 产品级客户端用法。直接根据NetUri创建相应客户端 var client = new NetUri("tcp://smart.peacemoon.cn:17").CreateRemote(); client.Received += (s, e) => { XTrace.WriteLine("收到:{0}", e.ToStr()); }; client.Open(); Thread.Sleep(1000); }
/// <summary>设置父级DNS</summary> /// <param name="parents"></param> public virtual void SetParents(String parents) { var ss = parents.Split(","); if (ss == null || ss.Length < 1) { return; } var ps = Parents; var list = new HashSet <String>(ps.Select(p => p.ToString()), StringComparer.OrdinalIgnoreCase); //ps.Clear(); for (int i = ss.Length - 1; i >= 0; i--) { var uri = new NetUri(ss[i]); if (uri.Port <= 0) { uri.Port = 53; } if (!list.Contains(uri.ToString())) { if (uri.Address.IsAny()) { WriteLog("配置的父级DNS[{0}]有误,任意地址不能作为父级DNS地址。", uri); continue; } ps.Insert(0, uri); list.Add(uri.ToString()); } } }
/// <summary>异步发出请求,并接收响应</summary> /// <param name="uri"></param> /// <param name="data"></param> /// <returns></returns> public virtual async Task <Packet> SendAsync(Uri uri, Byte[] data) { var remote = new NetUri(NetType.Tcp, uri.Host, uri.Port); // 构造请求 var req = BuildRequest(uri, data); StatusCode = -1; // 发出请求 var rs = await SendDataAsync(uri, req); if (rs == null || rs.Count == 0) { return(null); } // 解析响应 rs = ParseResponse(rs); // 头部和主体分两个包回来 if (rs != null && rs.Count == 0 && ContentLength != 0) { rs = await SendDataAsync(null, null); } // chunk编码 if (rs.Count > 0 && Headers["Transfer-Encoding"].EqualIgnoreCase("chunked")) { rs = ParseChunk(rs); } return(rs); }
/// <summary>添加服务器</summary> /// <param name="uri"></param> public IApiServer Add(NetUri uri) { Type type; if (!Providers.TryGetValue(uri.Protocol, out type)) { return(null); } var svr = type.CreateInstance() as IApiServer; if (svr != null) { svr.Provider = this; svr.Log = Log; if (!svr.Init(uri.ToString())) { return(null); } } Servers.Add(svr); return(svr); }
/// <summary>打开</summary> protected override Boolean OnOpen() { // 默认80端口 if (!Active && Remote.Port == 0) { Remote.Port = 80; } if (Remote.Address.IsAny()) { Remote = new NetUri(Request.Url + ""); } //Request.Method = Method; //Request.Url = Url; // 添加过滤器 if (SendFilter == null) { SendFilter = new HttpRequestFilter { Client = this } } ; return(base.OnOpen()); }
static Int32 WorkOne(NetUri uri, Config cfg, Packet pk) { var count = 0; try { var client = uri.CreateRemote(); (client as SessionBase).MaxAsync = 0; client.Open(); for (var k = 0; k < cfg.Times; k++) { client.Send(pk); if (cfg.Reply) { var pk2 = client.Receive(); if (pk2.Count > 0) { count++; } } else { count++; } } } catch { } return(count); }
/// <summary>根据本地网络标识创建客户端</summary> /// <param name="local"></param> /// <returns></returns> public static ISocketClient CreateClient(this NetUri local) { if (local == null) { throw new ArgumentNullException("local"); } switch (local.Type) { case NetType.Tcp: var tcp = new TcpSession { Local = local }; return(tcp); case NetType.Udp: var udp = new UdpServer { Local = local, UseReceiveAsync = true }; return(udp); default: throw new NotSupportedException("不支持{0}协议".F(local.Type)); } }
/// <summary>根据远程网络标识创建客户端</summary> /// <param name="remote"></param> /// <returns></returns> public static ISocketClient CreateRemote(this NetUri remote) { if (remote == null) { throw new ArgumentNullException(nameof(remote)); } switch (remote.Type) { case NetType.Tcp: return(new TcpSession { Remote = remote }); case NetType.Udp: return(new UdpServer { Remote = remote }); //case NetType.Http: // var http = new HttpClient { Remote = remote }; // //http.IsSSL = remote.Protocol.EqualIgnoreCase("https"); // return http; //case NetType.WebSocket: // var ws = new HttpClient { Remote = remote }; // //ws.IsSSL = remote.Protocol.EqualIgnoreCase("https"); // ws.IsWebSocket = true; // return ws; default: throw new NotSupportedException("不支持{0}协议".F(remote.Type)); } }
/// <summary>根据远程网络标识创建客户端</summary> /// <param name="remote"></param> /// <returns></returns> public static ISocketClient CreateRemote(this NetUri remote) { if (remote == null) { throw new ArgumentNullException("remote"); } switch (remote.Type) { case NetType.Tcp: var tcp = new TcpSession { Remote = remote }; return(tcp); case NetType.Udp: var udp = new UdpServer { Remote = remote, UseReceiveAsync = true }; return(udp); default: throw new NotSupportedException("不支持{0}协议".F(remote.Type)); } }
public void ParseAddress() { var addrs = NetUri.ParseAddress("www.newlifex.com"); Assert.NotNull(addrs); //Assert.Equal(3, addrs.Length); Assert.True(addrs.Length > 0); Assert.Contains(addrs, e => e.AddressFamily == AddressFamily.InterNetwork); if (addrs.Length > 1) { Assert.Contains(addrs, e => e.AddressFamily == AddressFamily.InterNetworkV6); } var addrs2 = NetUri.ParseAddress("240e:e0:9930:2100:9914:b410:c7d8:c0a6"); Assert.NotNull(addrs2); Assert.Single(addrs2); Assert.Equal("240e:e0:9930:2100:9914:b410:c7d8:c0a6", addrs2[0] + ""); var uri = new NetUri("https://www.newlifex.com"); Assert.Equal("www.newlifex.com", uri.Host); var addrs3 = uri.GetAddresses(); //Assert.Equal(3, addrs3.Length); Assert.True(addrs.Length > 0); }
/// <summary>创建客户端会话</summary> /// <param name="uri"></param> /// <returns></returns> protected virtual HttpClient Create(NetUri uri) { var http = uri.CreateRemote() as HttpClient; http.Log = Log; //if (XTrace.Debug) //{ // http.LogSend = true; // http.LogReceive = true; //} var req = http.Request; req.UserAgent = UserAgent; if (AutomaticDecompression != DecompressionMethods.None) { req.Compressed = true; } //if (!String.IsNullOrEmpty(Accept)) req.Headers[HttpRequestHeader.Accept + ""] = Accept; //if (!String.IsNullOrEmpty(AcceptLanguage)) req.Headers[HttpRequestHeader.AcceptLanguage + ""] = AcceptLanguage; //if (!String.IsNullOrEmpty(Referer)) req.Headers[HttpRequestHeader.Referer + ""] = Referer; req.Accept = Accept; req.AcceptLanguage = AcceptLanguage; req.Referer = Referer; return(http); }
/// <summary>根据本地网络标识创建客户端</summary> /// <param name="local"></param> /// <returns></returns> public static ISocketClient CreateClient(this NetUri local) { if (local == null) { throw new ArgumentNullException(nameof(local)); } switch (local.Type) { case NetType.Tcp: return(new TcpSession { Local = local }); case NetType.Udp: return(new UdpServer { Local = local }); case NetType.Http: return(new HttpClient { Local = local }); default: throw new NotSupportedException("不支持{0}协议".F(local.Type)); } }
static void TestClient() { var uri = new NetUri("tcp://::1:1234"); //var uri = new NetUri("tcp://net.newlifex.com:1234"); var client = uri.CreateRemote(); client.Log = XTrace.Log; client.LogSend = true; client.LogReceive = true; client.Received += (s, e) => { XTrace.WriteLine("收到:{0}", e.Packet.ToStr()); }; client.Open(); // 定时显示性能数据 _timer = new TimerX(ShowStat, client, 100, 1000); // 循环发送数据 for (var i = 0; i < 5; i++) { Thread.Sleep(1000); var str = "你好" + (i + 1); client.Send(str); } client.Dispose(); }
/// <summary>设置远程地址</summary> /// <param name="uri"></param> /// <returns></returns> public Boolean SetRemote(String uri) { Type type; var nu = new NetUri(uri); if (!Providers.TryGetValue(nu.Type + "", out type)) { return(false); } WriteLog("{0} SetRemote {1}", type.Name, nu); if (type.CreateInstance() is IApiClient ac) { ac.Provider = this; ac.Log = Log; if (ac.Init(uri)) { Client.TryDispose(); Client = ac; } } return(true); }
private void Connect() { _Client = null; var remote = cbRemote.Text; var uri = new NetUri(remote); if (uri.Type == NetType.Unknown) { uri.Type = NetType.Tcp; } if (uri.Port == 0) { uri.Port = 22; } var client = new SshClient(uri.Host ?? (uri.Address + ""), uri.Port, txtUser.Text, txtPass.Text); client.ErrorOccurred += Client_ErrorOccurred; client.Connect(); _Client = client; "已连接服务器".SpeechTip(); pnlSetting.Enabled = false; btnConnect.Text = "关闭"; _config.Save(); }
static void TestClient() { var uri = new NetUri("tcp://127.0.0.1:1234"); //var uri = new NetUri("tcp://net.newlifex.com:1234"); var client = uri.CreateRemote(); client.Log = XTrace.Log; client.Received += (s, e) => { var pk = e.Message as Packet; XTrace.WriteLine("收到:{0}", pk.ToStr()); }; //client.Add(new LengthFieldCodec { Size = 4 }); client.Add <StandardCodec>(); // 打开原始数据日志 var ns = client; ns.LogSend = true; ns.LogReceive = true; client.Open(); // 定时显示性能数据 _timer = new TimerX(ShowStat, client, 100, 1000); // 循环发送数据 for (var i = 0; i < 5; i++) { var str = "你好" + (i + 1); var pk = new Packet(str.GetBytes()); client.SendMessageAsync(pk); } }
/// <summary>创建连接客户端</summary> /// <returns></returns> protected virtual RedisClient OnCreate() { var svr = Server; if (svr.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(Server)); } if (!svr.Contains("://")) { svr = "tcp://" + svr; } var uri = new NetUri(svr); if (uri.Port == 0) { uri.Port = 6379; } var rc = new RedisClient { Host = this, Server = uri, //Password = rds.Password, //Db = rds.Db, }; rc.Log = Log; //if (rds.Db > 0) rc.Select(rds.Db); return(rc); }
/// <summary>创建连接客户端</summary> /// <returns></returns> protected virtual RedisClient OnCreate() { var svr = Server?.Trim(); if (svr.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(Server)); } if (!svr.Contains("://")) { svr = "tcp://" + svr; } var uri = new NetUri(svr); if (uri.Port == 0) { uri.Port = 6379; } var rc = new RedisClient(this, uri) { Log = Log }; //if (rds.Db > 0) rc.Select(rds.Db); return(rc); }
public void TcpEmptyData() { var server = new NetServer { Port = 7777, Log = XTrace.Log, SessionLog = XTrace.Log, SocketLog = XTrace.Log, LogSend = true, LogReceive = true, }; server.Received += (s, e) => { var ss = s as INetSession; ss.Send(e.Packet); }; server.Start(); { var uri = new NetUri($"tcp://127.0.0.1:{server.Port}"); var client = new TcpClient(); client.Connect(uri.EndPoint); var ns = client.GetStream(); ns.Write("*****@*****.**".GetBytes()); var buf = new Byte[1024]; var rs = ns.Read(buf, 0, buf.Length); } Thread.Sleep(10_000); }
/// <summary>获取网络数据流</summary> /// <param name="uri"></param> /// <returns></returns> protected virtual async Task <Stream> GetStreamAsync(Uri uri) { var tc = Client; var ns = _stream; // 判断连接是否可用 var active = false; try { active = tc != null && tc.Connected && ns != null && ns.CanWrite && ns.CanRead; if (active) { return(ns); } ns = tc?.GetStream(); active = tc != null && tc.Connected && ns != null && ns.CanWrite && ns.CanRead; } catch { } // 如果连接不可用,则重新建立连接 if (!active) { var remote = new NetUri(NetType.Tcp, uri.Host, uri.Port); tc.TryDispose(); tc = new TcpClient { ReceiveTimeout = (Int32)Timeout.TotalMilliseconds }; await tc.ConnectAsync(remote.Address, remote.Port).ConfigureAwait(false); Client = tc; ns = tc.GetStream(); if (BaseAddress == null) { BaseAddress = new Uri(uri, "/"); } active = true; } // 支持SSL if (active) { if (uri.Scheme.EqualIgnoreCase("https")) { var sslStream = new SslStream(ns, false, (sender, certificate, chain, sslPolicyErrors) => true); await sslStream.AuthenticateAsClientAsync(uri.Host, new X509CertificateCollection(), SslProtocols.Tls12, false).ConfigureAwait(false); ns = sslStream; } _stream = ns; } return(ns); }
public void TestRandomEmailUriPersonal() { var testResult = Email.RandomEmail(NetUri.RandomUsername("Robert", "Lee")); Assert.IsNotNull(testResult); Assert.IsTrue(testResult.Value.ToLower().Contains("lee")); Console.WriteLine(testResult); }
/// <summary>使用本地DNS配置创建DNS客户端</summary> public DNSClient() { var addr = NetHelper.GetDns().FirstOrDefault(); if (addr != null) { Server = new NetUri(NetType.Udp, addr, 53); } }
public void TestToUri() { var testSubject = new NetUri { Value = "http://localhost:8993/Somewhere/", Descriptor = KindsOfLabels.Home }; var testResult = testSubject.ToUri(); Assert.IsNotNull(testResult); }
static void TestSend(String name, NetUri uri, Boolean isAsync, Boolean isSendData, Boolean isReceiveData) { Console.WriteLine(); String msg = String.Format("{0}Test_{1}_{2}!", name, uri.Type, isAsync ? "异步" : "同步"); var client = uri.CreateRemote(); client.Error += OnError; if (isAsync && isReceiveData) { _are.Reset(); client.Received += OnReceived; client.Open(); } if (isSendData) { client.Send(msg); } var rs = false; if (isReceiveData) { if (!isAsync) { try { //Console.WriteLine("客户端" + session + " " + session.ReceiveString()); var pk = client.Receive(); Console.WriteLine("客户端{0} 收到 [{1}]: {2}", client, pk.Count, pk.ToStr()); rs = true; } catch (Exception ex) { Debug.Fail("同步超时!" + ex.Message); } } else { if (!_are.WaitOne(2000)) { Debug.Fail("异步超时!"); } else { rs = true; } } } client.Dispose(); client = null; GC.Collect(); XTrace.WriteLine(rs ? "成功!" : "失败!"); }
private Boolean ProcessConnect(HttpRequest request, ReceivedEventArgs e) { using var span = Host.Tracer?.NewSpan("proxy:HttpProxyConnect", request.Url + ""); var pxy = Host as HttpProxy; var uri = new NetUri(request.Url.ToString()); var ruri = RemoteServerUri; ruri.Host = uri.Host; ruri.Port = uri.Port; // 不要连自己,避免死循环 if (uri.Port == pxy.Server.Port && uri.Address.IsLocal()) { WriteLog("不要连自己,避免死循环"); Dispose(); return(false); } var rs = new HttpResponse { Version = request.Version }; try { // 连接远程服务器,启动数据交换 if (RemoteServer == null) { ConnectRemote(e); } // 响应头增加所使用的本地IP地址,让客户端知道 rs.Headers["Proxy-Local-Ip"] = RemoteServer?.Local.Address + ""; rs.StatusCode = HttpStatusCode.OK; rs.StatusDescription = "OK"; } #if NET5_0 catch (HttpRequestException ex) { rs.StatusCode = ex.StatusCode ?? HttpStatusCode.BadRequest; rs.StatusDescription = ex.Message; } #endif catch (Exception ex) { rs.StatusCode = HttpStatusCode.BadGateway; rs.StatusDescription = ex.Message; } // 告诉客户端,已经连上了服务端,或者没有连上,这里不需要向服务端发送任何数据 Send(rs.Build()); return(false); }
// 如果是外部传进来的Socket,也销毁,就麻烦大了 ///// <summary>子类重载实现资源释放逻辑时必须首先调用基类方法</summary> ///// <param name="disposing">从Dispose调用(释放所有资源)还是析构函数调用(释放非托管资源)</param> //protected override void OnDispose(bool disposing) //{ // base.OnDispose(disposing); // if (_Socket != null) // { // _Socket.Dispose(); // _Socket = null; // } // if (_Socket2 != null) // { // _Socket2.Dispose(); // _Socket2 = null; // } //} #endregion #region 方法 void EnsureSocket() { if (_Socket == null) { //var client = NetService.Container.Resolve<ISocketClient>(ProtocolType); //client.Port = Port; var client = new NetUri(ProtocolType, "", Port).CreateClient(); client.Open(); client.Client.SendTimeout = Timeout; client.Client.ReceiveTimeout = Timeout; _Socket = client; } }
void EnsureSocket2() { if (_Socket2 == null) { var socket = Socket.Client; var ep = socket.LocalEndPoint as IPEndPoint; var sto = socket.SendTimeout; var rto = socket.ReceiveTimeout; // 如果原端口没有启用地址重用,则关闭它 Object value = socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress); if (!Convert.ToBoolean(value)) socket.Close(); //var sk = NetService.Container.Resolve<ISocketClient>(socket.ProtocolType); ////sk.Address = ep.Address; ////sk.Port = ep.Port; //sk.Local.EndPoint = ep; var sk = new NetUri((NetType)socket.ProtocolType, ep).CreateClient(); sk.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //sk.Bind(); sk.Client.SendTimeout = sto; sk.Client.ReceiveTimeout = rto; _Socket2 = sk; } }