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("连接服务器失败"); } }
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 void btnListen_Click(object sender, EventArgs e) { isLineDebug = false; var data = Encoding.UTF8.GetBytes(txtMsg.Text.Trim() + Environment.NewLine); tcpClient.Send(new ArraySegment <byte>(data, 0, data.Length)); WriteInfo($"发送 {txtMsg.Text.Trim()}"); }
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 async Task LoginToSocketAsync() { if (!client.IsConnected) { await ConnectAsync(); } string msg = "LOGIN " + id.ToString() + "\r\n"; Logger.Write("Send message " + msg); client.Send(Encoding.ASCII.GetBytes(msg)); }
private async void connectServer() { client = new EasyClient <MyPackageInfo>(); client.Initialize(new MyReceiveFilter()); client.Connected += OnClientConnected; client.NewPackageReceived += OnPackageReceived; client.Error += OnClientError; client.Closed += OnClientClosed; var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(txtIP.Text.ToString().Trim()), int.Parse(txtPort.Text.ToString().Trim()))); if (connected) { //name 2 length 2 body 6 bit 心跳包 var rs = new List <byte> { 0, 1, 0, 6 }; string timeLogin = DateTime.Now.ToString("1ssfff"); //rs.AddRange(System.Text.Encoding.UTF8.GetBytes(timeLogin)); //LogHelper.WriteLog("发送login数据:" + DataHelper.ByteToHex(rs.ToArray(), rs.Count)); //client.Send(rs.ToArray()); byte[] dataHeart = HeartToPack(txtNickName.Text.ToString().Trim(), txtIDType.Text.ToString().Trim()); LogHelper.WriteLog("发送 Login 26 数据:" + DataHelper.ByteToHex(dataHeart.ToArray(), dataHeart.Length)); client.Send(dataHeart.ToArray()); //每5秒发一次心跳 timer = new System.Timers.Timer(20000); timer.Elapsed += new System.Timers.ElapsedEventHandler((s, x) => { if (client.IsConnected && cbHeart.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()); //string timeIDHeart = "#" + txtNickName.Text.ToString().Trim() + "#" + txtIDType.Text.ToString().Trim(); //rs.AddRange(System.Text.Encoding.UTF8.GetBytes(timeIDHeart.PadLeft(26, '$'))); //LogHelper.WriteLog("发送数据:" + DataHelper.ByteToHex(rs.ToArray(), rs.Count) + " Heart Length " + rs.Count + " " + timeIDHeart); //client.Send(rs.ToArray()); dataHeart = HeartToPack(txtNickName.Text.ToString().Trim(), txtIDType.Text.ToString().Trim()); LogHelper.WriteLog("发送 Heart 26 数据:" + DataHelper.ByteToHex(dataHeart.ToArray(), dataHeart.Length)); client.Send(dataHeart.ToArray()); } }); timer.Enabled = true; timer.Start(); } else { LogHelper.WriteLog("连接服务器失败"); } }
//连接服务器 public async void ConnectToServer(string ip, int port) { this.ip = ip; this.port = port; var data = "hello this is super client\r\n"; var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port)); if (connected) { client.Send(Encoding.ASCII.GetBytes(data)); } }
/// <summary> /// 发送命令和消息到服务器 /// </summary> /// <param name="command"></param> /// <param name="message"></param> public static void SendMessage(DeviceFunCodeEnum command, string message) { if (client == null || !client.IsConnected || message.Length <= 0) { return; } var response = BitConverter.GetBytes((ushort)command).Reverse().ToList(); var arr = System.Text.Encoding.UTF8.GetBytes(message); response.AddRange(BitConverter.GetBytes((ushort)arr.Length).Reverse().ToArray()); response.AddRange(arr); client.Send(response.ToArray()); LogHelper.Log.Info($"发送{command.GetDescription()}数据:" + message + " byte:" + BitConverter.ToString(response.ToArray())); }
private void OnPackageReceived(object sender, PackageEventArgs <MyPackageInfo> e) { LogHelper.WriteLog("收到文本下行:" + e.Package.Body); //16进制 //LogHelper.WriteLog("下行:" + DataHelper.ByteToHex(e.Package.Header, e.Package.Header.Length) + DataHelper.ByteToHex(e.Package.Data, e.Package.Data.Length)); //回复服务端确认 if ((e.Package.Header[0] * 256 + e.Package.Header[1]) == 4) { var arr = new List <byte> { 0, 4, 0, 1, 1 }; client.Send(arr.ToArray()); } }
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 override void SendData(byte[] data) { if (client.IsConnected) { client.Send(data); } }
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); } }
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(); }
/// <summary> /// 通过Socket发送日志 /// </summary> /// <param name="level">日志级别</param> /// <param name="beginMark">Stocket信息头</param> /// <param name="endMark">Socket信息尾</param> /// <param name="logRequest">日志请求</param> private static void SendMessage(LogLevel level, string beginMark, string endMark, LogRequest logRequest) { var pack = new StringPackageInfo(level.ToString(), logRequest.ToJson(), null); var msg = $"{beginMark}{pack.ToJson()}{endMark}"; client.Send(Encoding.UTF8.GetBytes(msg)); }
/// <summary> /// 客户端向服务器发送消息 /// </summary> /// <param name="client">客户端对象</param> /// <param name="command">命令</param> /// <param name="msg">数据包</param> public static void Send(this EasyClient <CustomPackageInfo> client, CustomCommand command, string msg) { if (client != null && client.IsConnected && !string.IsNullOrEmpty(msg)) { byte[] data = GetMsgBytes(msg, command); client.Send(data); } }
public void Send(string _message) { if (_tcpClient.IsConnected) { var temp = Encoding.Default.GetBytes(_message); _tcpClient.Send(temp); } }
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; var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18888)); 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"))); LogHelper.WriteLog("发送数据:" + DataHelper.ByteToHex(rs.ToArray(), rs.Count)); client.Send(rs.ToArray()); //每5秒发一次心跳 timer = new System.Timers.Timer(50000); timer.Elapsed += new System.Timers.ElapsedEventHandler((s, x) => { if (client.IsConnected && cbHeart.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()); LogHelper.WriteLog("发送数据:" + DataHelper.ByteToHex(rs.ToArray(), rs.Count)); client.Send(rs.ToArray()); } }); timer.Enabled = true; timer.Start(); } else { LogHelper.WriteLog("连接服务器失败"); } }
public Task Send(EasyClient client) { Wait = new AutoResetEvent(false); return(Task.Run(() => { client.Send(Request.BuildBytes()); })); }
private void HeartBeatCallBack(object state) { try { tmrHeartBeat.Change(Timeout.Infinite, Timeout.Infinite); if (tcpPassiveEngine != null && tcpPassiveEngine.IsConnected)//与客户端连接成功后发送消息 { var sbMessage = new StringBuilder(); sbMessage.AppendFormat(string.Format("heartbeat {0}\r\n", "心跳数据包:ok")); var data = Encoding.UTF8.GetBytes(sbMessage.ToString()); tcpPassiveEngine.Send(new ArraySegment <byte>(data, 0, data.Length)); } } finally { tmrHeartBeat.Change(mHeartBeatInterval, mHeartBeatInterval); } }
public void Send(Dictionary <string, object> args) { DouyuPackageInfo package = new DouyuPackageInfo(); string argsStr = DouyuUtility.Serialize(args); byte[] data = package.Encode(argsStr); client.Send(new ArraySegment <byte>(data)); }
async void EchoAsync(EasyClient <StringPackageInfo> client, string msg) { await Task.Factory.StartNew(() => { msg = string.Format("echo {0}", msg + Environment.NewLine); byte[] bMsg = System.Text.Encoding.UTF8.GetBytes(msg); client.Send(new ArraySegment <byte>(bMsg, 0, bMsg.Length)); }); }
public void Send(string sendContent) { if (client != null && client.IsConnected) { sendContent += "\r\n"; var data = Encoding.UTF8.GetBytes(sendContent.ToString()); client.Send(new ArraySegment <byte>(data, 0, data.Length)); // client.Send(Encoding.ASCII.GetBytes("ADD*1#2 \r\n")); } }
public double Calculate(MessagePackageInfo messagePackageInfo) { _easyClient.Send(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(messagePackageInfo) + "\r\n")); AutoResetEvent autoResetEvent = new AutoResetEvent(false); bool waited = autoResetEvent.WaitOne(TimeSpan.FromSeconds(5)); if (!waited) { throw new TimeoutException(); } }
/// <summary> /// 发送消息 /// </summary> /// <param name="mq">消息实体内容</param> /// <returns></returns> public bool SendMessage(Common.Mode.MQModel mq) { try { string str = Newtonsoft.Json.JsonConvert.SerializeObject(mq); System.Threading.Interlocked.Increment(ref _instanceNumber); Logger.Info($"发送【普通】消息 编号:【{_instanceNumber}】内容:【{str}】"); var msg = Common.MQTools.GetSendMessage((byte)Common.CommanCode.SendMessage, str, _instanceNumber, mqType: 0); easyClient.Send(msg); return(true); } catch (Exception e) { System.Threading.Interlocked.Decrement(ref _instanceNumber); Logger.Error(mq, e); return(false); } }
private void Form1_Load(object sender, EventArgs e) { client.BeginConnect(new IPEndPoint(IPAddress.Parse("192.168.137.22"), 2020)); client.Initialize(new CallMessageFilter(), request => { }); if (client.IsConnected) { client.Send(GetBytes("CHECK:127.0.0.1\r\n")); } }
static void Main(string[] args) { SocketClientEasyClient client = new SocketClientEasyClient(new IPEndPoint(IPAddress.Parse("192.168.31.38"), 9005)); EasyClient <CustomPackageInfo> res = client.InitEasyClient(); while (Console.ReadLine() != "") { string data = Console.ReadLine(); string json = data.GetTransmitPackets(SocketCommand.SystemMessage); res.Send(SocketCommand.SystemMessage, json); } }
private void OnClientConnected(object sender, EventArgs e) { this.Dispatcher.BeginInvoke(new Action(() => { if (client.IsConnected) { if (JData == null) { JObject obj = new JObject(); obj["request"] = "active checks"; obj["host"] = "Dell Laptop"; var sendMsg = ZabbixProtocol.WriteWithHeader(obj); client.Send(sendMsg); } else { JObject obj = new JObject(); obj["request"] = "agent data"; JArray jArray = new JArray(); var data = JData.SelectToken("data") as JArray; foreach (var da in data) { JObject dataObj = new JObject(); dataObj["key"] = da["key"] + ""; dataObj["host"] = "Dell Laptop"; dataObj["value"] = "98"; //dataObj["clock"] = DateTime.Now.Ticks; dataObj["ns"] = 76808644; jArray.Add(dataObj); } obj["data"] = jArray; var sendMsg = ZabbixProtocol.WriteWithHeader(obj); client.Send(sendMsg); } } })); }
public void SendMessage(EMessage msgType, ushort flag = 0) { if (!IsConnected()) { return; } ushort _size = 0; byte[] _sizeBuffer = BitConverter.GetBytes(_size); byte[] _typeBuffer = BitConverter.GetBytes((ushort)msgType); byte[] _flagBuffer = BitConverter.GetBytes(flag); _memoryStream.SetLength(0L); _memoryStream.Position = 0; _memoryStream.Write(_typeBuffer, 0, 2); _memoryStream.Write(_flagBuffer, 0, 2); _memoryStream.Write(_sizeBuffer, 0, 2); byte[] _buffer = _memoryStream.ToArray(); m_client.Send(_buffer); }
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); }