public override void DoWork(bool stopping) { if (client == null) { var client = new EasyClient(); bool connected; client.NoDelay = true; client.Initialize(new ReceiveFilter(), (request) => { }); connected = client.ConnectAsync(new IPEndPoint(IPAddress.Parse(this.Address), this.Port)).Result; if (connected) { this.client = client; SendQueuedItems(); } else { Thread.Sleep(100); } } else { SendQueuedItems(); } }
public Communication() { m_Client = new EasyClient <BufferedPackageInfo>(); m_Client.ReceiveBufferSize = AppConfiger.AppCfg.CurrCC_Cfg.MaxRequestLength; //m_Client.ReceiveBufferSize = 1024 * 1024 * 10; m_Client.Connected += TcpSession_Connected; m_Client.NewPackageReceived += TcpSession_PackageReceived;; m_Client.Error += (sender, e) => { //重连 if (!this.IsConnected) { if (this.m_ReconnectCount < MAX_RECONNECT_COUNT) { this.m_ReconnectCount++; Console.WriteLine("{0} 尝试重连,5秒后重试……", this.m_ReconnectCount); Thread.Sleep(1000 * 5); this.Connect(this.ConnectOptions); } else { this.ErrorCallbackHandler?.Invoke(e.Exception); } } }; m_Client.Initialize(new ReceiveFilter()); }
public async Task TestConnectRepeat() { var client = new EasyClient(); client.Initialize(new FakeReceiveFilter(), (p) => { // do nothing }); Console.WriteLine("Connecting"); var ret = await client.ConnectAsync(new DnsEndPoint("github.com", 443)); Console.WriteLine("Connected"); Assert.True(ret); Console.WriteLine("Closing"); await client.Close(); Console.WriteLine("Closed"); Console.WriteLine("Connecting"); ret = await client.ConnectAsync(new DnsEndPoint("github.com", 443)); Console.WriteLine("Connected"); Assert.True(ret); Console.WriteLine("Closing"); await client.Close(); Console.WriteLine("Closed"); }
private static async void CreateSocket(int clientId, EndPoint remoteEndPoint) { await Task.Run(async() => { try { var client = new EasyClient(); var port = int.Parse(ConfigurationManager.AppSettings["LocalPort"]); if (port != 0) { client.LocalEndPoint = new IPEndPoint(IPAddress.Any, port); } client.Initialize(new ReceiveFilter(), ReceiveHandler); var isConnected = await client.ConnectAsync(remoteEndPoint); if (isConnected) { _allClients.TryAdd(client.LocalEndPoint.ToString(), new Tuple <int, EasyClient>(clientId, client)); } else { Console.WriteLine($"Client:{clientId} connect service faild!"); } } catch (Exception ex) { Console.WriteLine(ex); } }); }
/// <summary> /// 构造函数 /// </summary> /// <param name="ip">服务器的ip</param> /// <param name="port">服务器的端口</param> public SocketClientHelper(string serverIp, int serverPort) { if (System.Net.IPAddress.TryParse(serverIp, out IPAddress tmpServerIp)) { if (!Equals(null, Error)) { Error(this, new FormatException("IP地址错误")); } } if (1024 < serverPort && serverPort > 65535) { if (!Equals(null, Error)) { Error(this, new FormatException("端口号错误")); } } try { this.ServerIp = serverIp; this.ServerPort = serverPort; easyClient.NoDelay = true; easyClient.Closed += EasyClient_Closed; easyClient.Connected += EasyClient_Connected; easyClient.Error += EasyClient_Error; easyClient.Initialize <PackageInfo>(new ReceiveFilter(), HandlerPackage); } catch (Exception ex) { if (!Equals(null, Error)) { Error(this, ex); } } }
public void Init() { TcpClient = new EasyClient <ClientPackageInfo>() { NoDelay = true //Security = new SecurityOption() //{ // EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12, // AllowNameMismatchCertificate = true, // AllowCertificateChainErrors = true, // AllowUnstrustedCertificate = true //} }; TcpClient.Initialize(new ClientReceiveFilter()); TcpClient.Connected += OnClientConnected; TcpClient.NewPackageReceived += OnPackageReceived; TcpClient.Error += OnClientError; TcpClient.Closed += OnClientClosed; var arr = PackJson.Local.Split(":"); var ip = arr[0]; int.TryParse(arr[1], out int port); mark: var res = TcpClient.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port)).Result; while (!res) { HandleLog.WriteLine($"{PackJson.UserId}连接{PackJson.Local}失败,1s后重新连接..."); Thread.Sleep(1000); goto mark; } LocalEndPoint = TcpClient.LocalEndPoint?.ToString(); }
public async Task C_ConnectEasyClientToHL7Interface() { HL7InterfaceBase hl7Interface = new HL7InterfaceBase(); AutoResetEvent newSessionConnectedSignal = new AutoResetEvent(false); AutoResetEvent welcomMessageReceived = new AutoResetEvent(false); Assert.IsTrue(hl7Interface.Initialize()); Assert.IsTrue(hl7Interface.Start()); hl7Interface.HL7Server.NewSessionConnected += (hl7Session) => { Assert.That(hl7Session is HL7Session); Assert.That(hl7Session.Connected); newSessionConnectedSignal.Set(); }; EasyClient client = new EasyClient(); client.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (packageInfo) => { //nothing }); Assert.IsTrue(client.ConnectAsync(endPointA).Result); Assert.That(client.IsConnected); Assert.That(newSessionConnectedSignal.WaitOne()); await client.Close(); hl7Interface.Stop(); }
static void Main(string[] args) { //var client = SuperEasyClient.ConnectServer(); //if(client.Result) //{ // var message = Console.ReadLine(); // while(string.IsNullOrEmpty(message)) // { // SuperEasyClient.SendMessage(message); // } //} var client = new EasyClient <MyPackageInfo>(); client.Initialize(new MyFilter()); client.NewPackageReceived += Client_NewPackageReceived; var connected = client.ConnectAsync(new IPEndPoint(IPAddress.Parse("192.168.11.167"), 2020)); if (connected.Result) { // Send data to the server client.Send(Encoding.ASCII.GetBytes("LOGIN kerry")); } while (true) { var message = Console.ReadLine(); client.Send(Encoding.ASCII.GetBytes(message)); } Console.ReadLine(); }
private static async void connectServer() { var client = new EasyClient(); client.Initialize(new MyReceiveFilter(), (request) => { //回复格式:地址 功能码 字节数 数值…… //01 03 02 00 01 地址:01 功能码:03 字节数:02 数据:00 01 Console.WriteLine(DateTime.Now + " 收到16进制数据:" + request.HexAllData); }); var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10000)); if (connected) { Console.WriteLine("已连接到服务器..."); while (client.IsConnected) { client.Send(DataHelper.HexToByte(GetByteA(new Random().Next(5, 20)))); Thread.Sleep(2000); client.Send(DataHelper.HexToByte(GetByteB(new Random().Next(5, 20)))); Thread.Sleep(2000); } } else { Console.WriteLine("连接服务器失败"); } }
public void Initialize() { _easyClient = new EasyClient(); _easyClient.Initialize(new MyReceiveFilter(), new Action <MessagePackageInfo>((msg) => { })); }
public MyClient(ProgramType _programType) { programType = _programType; client = new EasyClient(); client.Initialize(new MyReceiveFilter(), (response) => { try { Loger.LogMessage("收到消息:" + JsonHelper.SerializeObj(response)); OnReveieveData(response); } catch (Exception ex) { Loger.LogMessage(ex.ToString()); } }); if (programType == ProgramType.Student) { OnReveieveData += Student_OnReveieveData; } else { OnReveieveData += Teacher_OnReveieveData; } _connected = client.ConnectAsync(new IPEndPoint(IPAddress.Parse(serverIP), serverPort)).Result; }
public void Connect() { Task <bool> task = client.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1222)); bool res = task.Result; client.Initialize(new MyFilter(), new Action <StringPackageInfo>(OnReceived)); }
public async Task G_AppServerWelcomeOnEasyClientNewSessionConnected() { AppServer appServer = new AppServer(); Assert.IsTrue(appServer.Setup("127.0.0.1", 50060)); Assert.IsTrue(appServer.Start()); appServer.NewSessionConnected += (s) => { s.Send("Welcome!"); }; EasyClient easyClient = new EasyClient(); AutoResetEvent callbackEvent = new AutoResetEvent(false); easyClient.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (p) => { callbackEvent.Set(); }); bool connected = await easyClient.ConnectAsync(serverEndpoint); Assert.IsTrue(connected); callbackEvent.WaitOne(timeout); await easyClient.Close(); appServer.Stop(); }
public async Task C_AppServerEasyClientNewSessionConnected() { AppServer appServer = new AppServer(); Assert.IsTrue(appServer.Setup("127.0.0.1", 50060)); Assert.IsTrue(appServer.Start()); AutoResetEvent sessionConnectedEvent = new AutoResetEvent(false); appServer.NewSessionConnected += (s) => { sessionConnectedEvent.Set(); }; EasyClient easyClient = new EasyClient(); AutoResetEvent helloReceivedEvent = new AutoResetEvent(false); easyClient.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (p) => { //do nothing }); bool connected = await easyClient.ConnectAsync(serverEndpoint); Assert.IsTrue(connected); sessionConnectedEvent.WaitOne(timeout); await easyClient.Close(); appServer.Stop(); }
private async void ConnectToServer(Dictionary <string, string> obj) { var client = new EasyClient <MyPackageInfo>(); client.Initialize(new NoReceiveFilter()); client.Connected += OnClientConnected; client.NewPackageReceived += OnPackageReceived; client.Error += OnClientError; client.Closed += OnClientClosed; var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(obj["IPAddress"]), Convert.ToInt32(obj["Port"]))); if (connected) { ClientConnectInfo sci = new ClientConnectInfo { ServerAddress = obj["IPAddress"] + ":" + obj["Port"], ServerPort = Convert.ToInt32(obj["Port"]), LocalEndPoint = client.LocalEndPoint.ToString(), IsConnected = "已连接" }; ClientConnectInfoList.Add(sci); ClientList.Add(client); } else { DXMessageBox.Show("连接服务端失败!", "提示"); } Messenger.Default.Unregister <Dictionary <string, string> >(this, "ConnectToServer", ConnectToServer); }
static void Main(string[] args) { var client = new EasyClient(); // Initialize the client with the receive filter and request handler client.Initialize(new MyReceiveFilter(), (request) => { // handle the received request Console.WriteLine($"{request.Key}, {request.Body}"); }); // Connect to the server var connected = client.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2020)).Result; if (connected) { Random r = new Random(100); // Send data to the server for (int i = 0; i < 100; i++) { client.Send(Encoding.ASCII.GetBytes($"ADD {r.Next(100)} {r.Next(100)}{Environment.NewLine}")); //Thread.Sleep(1000); } } client.Error += Client_Error; Console.ReadLine(); }
public async Task D_AppServerSendsWelcomeOnEasyClientNewSessionConnected() { AppServer appServer = new AppServer(); Assert.IsTrue(appServer.Setup("127.0.0.1", 50060)); Assert.IsTrue(appServer.Start()); AutoResetEvent welcomeReceiveEvent = new AutoResetEvent(false); appServer.NewSessionConnected += (s) => { s.Send("Welcome!"); }; EasyClient easyClient = new EasyClient(); easyClient.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (p) => { Assert.AreEqual("Welcome!", p.Key); welcomeReceiveEvent.Set(); }); bool x = easyClient.ConnectAsync(serverEndpoint).Result; welcomeReceiveEvent.WaitOne(); await easyClient.Close(); appServer.Stop(); }
public void SendText() { if (client == null) { client = new EasyClient(); client.Initialize(new ProtoBufReceiveFilter(), (msgWrapper) => { var person = Person.Parser.ParseFrom(msgWrapper.Msg.Message); Debug.Log(person.Name); Debug.Log(person.Age); }); } if (!client.IsConnected) { client.BeginConnect(new IPEndPoint(IPAddress.Parse(m_ServerIP), m_ServerPort)); return; } Person newPerson = new Person { Name = m_PlayerName, Age = m_Age }; m_MsgWrapper.Id = 200; m_MsgWrapper.Message = newPerson.ToByteString(); using (MemoryStream stream = new MemoryStream()) { var os = new CodedOutputStream(stream); os.WriteBytes(m_MsgWrapper.ToByteString()); os.Flush(); var data = stream.ToArray(); client.Send(data); } }
public MyClient(string endFilter) { if (string.IsNullOrEmpty(endFilter)) { this.endFilter = endFilter; } client = new EasyClient(); client.Initialize(new MyReceiveFilter(endFilter), (request) => { Console.WriteLine("resposen:" + request.Body); //收到服务器的发送CPU状态通知 if (request.Body.ToUpper().IndexOf("GETCPU") > -1) { if (!cycleSend) { StartSend(); } } //收到服务器的终止发送通知 else if (request.Body.ToUpper().IndexOf("STOPSENDING") > -1) { cycleSend = false; } }); cpuReader = new CpuTemperatureReader(); hs = cpuReader.GetTemperaturesInCelsius(); }
public async void Init() { client = new EasyClient(); client.Initialize(new MyTerminatorReceiveFilter(), (request) => { // handle the received request //syncManager.Add(() => //{ // callBack(request.Key, request.Body, request.Parameters); //}); Debug.Log(request.Body); //NGUIDebug.Log(request.Body); }); client.Error += (s, e) => { NGUIDebug.Log(e.Exception.Message); }; client.Closed += (s, e) => { }; // client.NewPackageReceived += Client_NewPackageReceived; // string IP = Config.parse("ServerIP"); var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse("192.168.100.68"), 9000)); if (connected) { // NGUIDebug.Log("connet success"); Debug.Log("connet success"); // Send data to the server client.Send(Encoding.ASCII.GetBytes("ADD*1#2 \r\n")); } }
public DouyuClient(string roomId, Action <Dictionary <string, object> > messageHandler) { RoomId = roomId; client = new EasyClient(); client.Initialize(new DouyuPackageFilter(), (package) => { messageHandler(DouyuUtility.Deserialize(package.Data)); }); }
public SocketClient() { client = new EasyClient(); client.Initialize(new MyReceiveFilter(), (response) => { OnReceiveData(response); }); }
public void Initialization() { m_client = new EasyClient(); m_client.Connected += OnConnected; m_client.Closed += OnClosed; m_client.Error += OnError; m_client.Initialize <MsgPackageInfo>(new MsgReceiveFilter(), OnReceivePackage); }
public async Task M_EasyCLientSendsCommandToHL7InterfaceWaitAckAndResponse() { HL7InterfaceBase hl7Interface = new HL7InterfaceBase(); AutoResetEvent ackReceived = new AutoResetEvent(false); AutoResetEvent commandResponseReceived = new AutoResetEvent(false); HL7Server serverSide = new HL7Server(); Assert.IsTrue(serverSide.Setup("127.0.0.1", 50060)); Assert.IsTrue(hl7Interface.Initialize(serverSide, new HL7ProtocolBase(new HL7ProtocolConfig()))); Assert.That(hl7Interface.Start()); hl7Interface.NewRequestReceived += (s, e) => { string response = MLLP.CreateMLLPMessage((new PrepareForSpecimenResponse()).Encode()); byte[] dataToSend = Encoding.ASCII.GetBytes(response); s.Send(dataToSend, 0, dataToSend.Length); }; PrepareForSpecimenRequest request = new PrepareForSpecimenRequest(); EasyClient client = new EasyClient(); client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) => { if (packageInfo.Request.IsAcknowledge) { Assert.That(packageInfo.Request is GeneralAcknowledgment); Assert.That(HL7Parser.IsAckForRequest(request, packageInfo.Request)); ackReceived.Set(); } else { Assert.IsTrue(packageInfo.Request is PrepareForSpecimenResponse); commandResponseReceived.Set(); } }); Assert.That(client.ConnectAsync(endPointA).Result); byte[] bytesToSend = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(request.Encode())); client.Send(bytesToSend); Assert.That(ackReceived.WaitOne()); Assert.That(commandResponseReceived.WaitOne()); await client.Close(); serverSide.Stop(); hl7Interface.Stop(); }
public async Task I_AppServerAndEasyClientReceivesMultiblePackages() { var filterFactory = new DefaultReceiveFilterFactory <TestBeginEndMarkReceiveFilter, StringRequestInfo>(); AppServer appServer = new AppServer(filterFactory); Assert.IsTrue(appServer.Setup("127.0.0.1", 50060)); Assert.IsTrue(appServer.Start()); int requestCount = 0; StringBuilder sb = new StringBuilder(); appServer.NewRequestReceived += (s, e) => { sb.Append(e.Key); if (++requestCount == 4) { Assert.AreEqual("Can you serve me?", sb.ToString()); byte[] data = Encoding.ASCII.GetBytes("|Sure, ||" + "|how ||" + "|can ||" + "|I ||" + "|help?||"); requestCount = 0; sb.Clear(); s.Send(data, 0, data.Length); } }; EasyClient easyClient = new EasyClient(); AutoResetEvent callbackEvent = new AutoResetEvent(false); StringBuilder sb1 = new StringBuilder(21); easyClient.Initialize(new TestProtoBaseBeginEndMarkReceiverFilter(), (p) => { sb.Append(p.OriginalRequest); if (++requestCount == 5) { Assert.AreEqual("Sure, how can I help?", sb.ToString()); callbackEvent.Set(); } }); bool connected = easyClient.ConnectAsync(serverEndpoint).Result; Assert.IsTrue(connected); easyClient.Send(Encoding.ASCII.GetBytes("#Can ##" + "#you ##" + "#serve ##" + "#me?##")); callbackEvent.WaitOne(timeout); await easyClient.Close(); appServer.Stop(); }
private async void connectServer() { client = new EasyClient <MyPackageInfo>(); client.Initialize(new MyReceiveFilter()); client.Connected += OnClientConnected; client.NewPackageReceived += OnPackageReceived; client.Error += OnClientError; client.Closed += OnClientClosed; int port = 0; if (!int.TryParse(txtPort.Text.Trim(), out port)) { AppEvents.Instance.OnUpdateScreenRun("端口设置错误"); return; } var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(txtIP.Text.Trim()), port)); if (connected) { //name 2 length 2 body 6 bit 心跳包 var rs = new List <byte> { 0, 1, 0, 6 }; rs.AddRange(System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("1ssfff"))); AppLog.Info("发送数据:" + DataHelper.ByteToHex(rs.ToArray(), rs.Count)); client.Send(rs.ToArray()); //每5秒发一次心跳 timer = new System.Timers.Timer(200000); timer.Elapsed += new System.Timers.ElapsedEventHandler((s, x) => { if (client.IsConnected && chkTimingHeart.Checked) { rs = new List <byte> { 0, 2, 0, 6 }; rs.AddRange(DateTime.Now.ToString("yy MM dd HH mm ss").Split(' ').Select(m => byte.Parse(m)).ToArray()); AppLog.Info("发送数据:" + DataHelper.ByteToHex(rs.ToArray(), rs.Count)); client.Send(rs.ToArray()); } }); timer.Enabled = true; timer.Start(); } else { AppLog.Info("连接服务器失败"); AppEvents.Instance.OnUpdateScreenRun("连接服务器失败"); } }
public TcpClient(string TerminalString) { Filter = new UserFilter(TerminalString); Client.Initialize(Filter, new Action <StringPackageInfo>(info => { })); Filter.OnPackageReceived += Filter_OnPackageReceived; Client.Connected += Client_Connected; Client.Closed += Client_Closed; }
public MyClient() { client = new EasyClient <MyPackageInfo>(); client.Initialize(new MyReceiveFilter()); client.Closed += Client_Closed; client.Error += Client_Error; client.Connected += Client_Connected; client.NewPackageReceived += Client_NewPackageReceived; }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) { client = new EasyClient<MyPackageInfo>(); client.Initialize(new ZabbixReceiveFilter()); client.Connected += OnClientConnected; client.NewPackageReceived += Client_NewPackageReceived1; client.Error += OnClientError; client.Closed += OnClientClosed; }
static void Main(string[] args) { EasyClient client = new EasyClient(); client.Initialize(new MyFilter(), (request) => { // handle the received request Console.WriteLine(request.Key); }); }
public async Task TestConnection() { var client = new EasyClient(); client.Initialize(new FakeReceiveFilter(), (p) => { // do nothing }); var ret = await client.ConnectAsync(new DnsEndPoint("github.com", 443)); Assert.True(ret); }
public async Task TestGet() { var client = new EasyClient(); //client.Security = new SecurityOption(); //client.Security.AllowUnstrustedCertificate = true; //client.Security.AllowNameMismatchCertificate = true; client.Error += (s, e) => { Console.WriteLine(e.Exception.Message); }; var taskCompleteSrc = new TaskCompletionSource<HttpPackageInfo>(); client.Initialize(new HttpReceiveFilter(), (p) => { taskCompleteSrc.SetResult(p); }); var ret = await client.ConnectAsync(new DnsEndPoint("www.supersocket.net", 80)); Assert.True(ret); Console.WriteLine("Get https connection established"); var sb = new StringBuilder(); sb.AppendLine("GET / HTTP/1.1"); sb.AppendLine("Accept: text/html, application/xhtml+xml, image/jxr, */*"); sb.AppendLine("Host: www.supersocket.net"); sb.AppendLine("Connection: Keep-Alive"); sb.AppendLine(); var data = Encoding.ASCII.GetBytes(sb.ToString()); client.Send(new ArraySegment<byte>(data, 0, data.Length)); var response = await taskCompleteSrc.Task; Console.WriteLine(response.Body); }