void client_Error(object sender, ErrorEventArgs e) { Console.WriteLine(e.Exception.Message); LogSingleton.LogHelper.Error(e.Exception.Message); if (!client.IsConnected) { client.Connect(p); } }
private void Form1_Load(object sender, EventArgs e) { if (!server.Setup(8888)) { return; } if (!server.Start()) { return; } server.NewSessionConnected += Server_NewSessionConnected; server.SessionClosed += Server_SessionClosed; server.NewRequestReceived += Server_NewRequestReceived; MyShowInfoDelgete = new ShowInfo((str, add) => { if (add) { listBox1.Items.Add(str); } else { listBox1.Items.Remove(str); } }); ShowClientRecv = new ShowInfo((str, add) => { textBox_ClientRecv.Text = str; }); client = new AsyncTcpSession(); client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888)); client.DataReceived += Client_DataReceived; client.NoDelay = true; }
void OnGUI() { if (GUI.Button(new Rect(100, 130, 100, 25), "SuperSocket")) { buffer.Data = new byte[8192]; IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(host), port); AsyncTcpSession client = new AsyncTcpSession(endPoint); client.Connected += OnConnected; client.DataReceived += OnDataReceive; client.Connect(); NamePacket.Builder b = new NamePacket.Builder(); b.SetName("Client name data"); NamePacket np = b.BuildPartial(); MemoryStream stream = new MemoryStream(); np.WriteTo(stream); byte[] bytes = stream.ToArray(); BasePacket.Builder basePacketBuilder = new BasePacket.Builder(); basePacketBuilder.SetPacketId(64553060); basePacketBuilder.SetPacketData( ByteString.CopyFrom(bytes) ); BasePacket basePacket = basePacketBuilder.BuildPartial(); sendMessage(client, basePacket); print("SuperSocket!"); } }
private void bConnect_Click(object sender, EventArgs e) { if (bConnect.Text == "Disconnect") { if (client != null) { client.Close(); client = null; } bConnect.Text = "Connect"; return; } try { client = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse(tServer.Text), Convert.ToInt32(tPort.Value))); #region // bind events client.Closed += client_Closed; client.Connected += client_Connected; client.DataReceived += client_DataReceived; client.Error += client_Error; #endregion AppendNotify("Connecting..."); bConnect.Text = "Disconnect"; client.Connect(); } catch (Exception ex) { AppendNotify("Connect failed: " + ex.Message); } }
static void Main(string[] args) { tcpSession = new AsyncTcpSession(); tcpSession.Connected += tcpSession_Connected; tcpSession.Closed += tcpSession_Closed; tcpSession.DataReceived += tcpSession_DataReceived; tcpSession.Error += tcpSession_Error; tcpSession.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000)); var tmpData = ""; while (tmpData != "q") { tmpData = Console.ReadLine(); var buffer = new CGD.buffer(50); buffer.append <int>(123); buffer.append <short>(0); buffer.append <string>(tmpData); buffer.set_front <short>(buffer.Count, 4); tcpSession.Send(buffer); } }
/// <summary> /// 定义一个client 每间隔10秒发送一次心跳,然后10分钟发送一次状态消息,借还购线等操作日志则马上传输 /// </summary> public void protobuf_checklink() { while (true) { string str = ""; try { if (bLoginFlag)//首先检测是否在线 { LaidianCommandModel.Builder laidianCommand = LaidianCommandModel.CreateBuilder(); laidianCommand.SetMessageType(MessageType.HEARTBEAT); sendMessage(client, laidianCommand.Build()); Thread.Sleep(500); } else { //连接服务器 client.Connect(); } } catch (IOException ex)//远程连接已经关闭 { } catch (Exception sd) { str = sd.Message; Console.WriteLine(str); } Thread.Sleep(3000); } }
static void Main(string[] args) { ServiceContainer.AddAndStartService(new ServiceInfo { Name = "DemoService", Factory = () => new DemoService() }); // ServiceContainer.AddAndStartService(new ServiceInfo { Name = "DemoService2",Factory = () => new DemoService2() }); ServiceProxy.CreateService <IDemoService>().Test(new TestCommand { Name = "sam", Password = "******" }); Console.ReadLine(); return; if (Console.ReadKey().KeyChar == 'd') { var serviceName = "DemoService"; var actionName = "Test"; var parameters = JsonConvert.SerializeObject(new TestCommand { Name = "test", Password = "******" }); var message = $"{serviceName}/{actionName}/{parameters}"; var session = new AsyncTcpSession(); var service = ServiceContainer.Services.First(a => a.Name == serviceName).GetInstance(); session.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), service.Communicator.Port)); session.Connected += Connected; session.Error += Error; session.DataReceived += DataReceived; session.Closed += Closed; while (!session.IsConnected) { Task.Delay(TimeSpan.FromMilliseconds(10)).GetAwaiter().GetResult(); } session.Send(message); // .ForEach(service => // { // // session.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), service.GetInstance().Communicator.Port)); // session.Connected += Connected; // session.Error += Error; // session.DataReceived += DataReceived; // session.Closed += Closed; // }); // var client = new EasyClient(); // client.Initialize(new Test(), req=> // { // Console.WriteLine(req.Body); // }); // ServiceContainer.Services.ForEach(service => // { // // if (client.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), service.GetInstance().Communicator.Port)).Result) // { // client.Send(Encoding.UTF8.GetBytes("cccccccccccccccc\r\n")); // } // }); Console.ReadLine(); } }
public static void ConnectServer() { tcpClient = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse("192.168.88.58"), 9004)); tcpClient.DataReceived += TcpClient_DataReceived; tcpClient.Error += TcpClient_Error; tcpClient.Closed += TcpClient_Closed; tcpClient.Connect(); }
internal void Connect() { Debugger.Log("begin connect->" + netClientId + "^" + currentHost + "^" + currentPort); if (inited && socketStatus == SocketStatus.NotConnet) { tcpSession.Connect(); } }
public void Connect(string ip, int port) { if (!_asyncTcpSession.IsConnected) { _asyncTcpSession.Connected += AsyncTcpSession_Connected;; _asyncTcpSession.DataReceived += AsyncTcpSession_DataReceived; _asyncTcpSession.Closed += AsyncTcpSession_Closed; _asyncTcpSession.Connect(new IPEndPoint(IPAddress.Parse(ip), port)); } }
public static void ConnectServer() { tcpClient = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 50000));//47.95.247.135,,192.168.1.104//192.168.82.107 tcpClient.DataReceived += TcpClient_DataReceived; //tcpClient.Error += TcpClient_Error; tcpClient.Closed += TcpClient_Closed; tcpClient.Connect(); log.Debug("RYZig网关客户端连接中……"); Console.WriteLine("RYZig网关客户端连接中……"); }
/// <summary> /// 建立连接 /// </summary> public void Start(string _ip, int _port) { ip = _ip; port = _port; client = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse(ip), port)); client.Connected += Connected; client.DataReceived += DataReceived; client.Error += Error; client.Closed += Closed; client.Connect(); }
public void A_TestAsyncTcpSession() { AppServer appServer = new AppServer(); Assert.IsTrue(appServer.Setup("127.0.0.1", 50060)); Assert.IsTrue(appServer.Start()); appServer.NewRequestReceived += (s, e) => { Assert.AreEqual("Hello!", e.Key); byte[] bytesToSend = Encoding.UTF8.GetBytes("Welcome!"); s.Send(bytesToSend, 0, bytesToSend.Length); }; AsyncTcpSession asyncTcpSession = new AsyncTcpSession(); asyncTcpSession.ReceiveBufferSize = 8; AutoResetEvent sessionDataReceivedEvent = new AutoResetEvent(false); asyncTcpSession.DataReceived += (s, e) => { string message = Encoding.ASCII.GetString(e.Data); Assert.AreEqual("Welcome!", message); sessionDataReceivedEvent.Set(); }; AutoResetEvent connectedEvent = new AutoResetEvent(false); asyncTcpSession.Connected += (s, e) => { connectedEvent.Set(); }; asyncTcpSession.Connect(serverEndpoint); Assert.IsTrue(connectedEvent.WaitOne(timeout)); Assert.IsTrue(asyncTcpSession.IsConnected); byte[] data = (Encoding.ASCII.GetBytes("Hello!" + Environment.NewLine)); asyncTcpSession.Send(data, 0, data.Length); sessionDataReceivedEvent.WaitOne(timeout); asyncTcpSession.Close(); appServer.Stop(); }
public NcsMain(Form1 form) { NcsTemplateBuffer.SetTempBuffer(); tcpSession = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse("192.168.0.17"), 65535)); tcpSession.Connected += tcpSession_Connected; tcpSession.Closed += tcpSession_Closed; tcpSession.DataReceived += tcpSession_DataReceived; tcpSession.Error += new EventHandler <ErrorEventArgs>(tcpSession_Error); tcpSession.Connect(); }
private AsyncTcpSession WSClient_ReConnect() { var wsClient = new AsyncTcpSession(); wsClient.Connected += new EventHandler(WSClient__Opened); wsClient.Closed += new EventHandler(WSClient__Closed); wsClient.Error += new EventHandler <SuperSocket.ClientEngine.ErrorEventArgs>(WSClient__Error); wsClient.DataReceived += new EventHandler <SuperSocket.ClientEngine.DataEventArgs>(WSClient_DataReceived); wsClient.ReceiveBufferSize = 1024 * 64; wsClient.Connect(ipp); return(wsClient); }
public NcsMain(IPEndPoint ipEndPoint, Form1 form) { NcsTemplateBuffer.SetTempBuffer(); tcpSession = new AsyncTcpSession(ipEndPoint); tcpSession.Connected += tcpSession_Connected; tcpSession.Closed += tcpSession_Closed; tcpSession.DataReceived += tcpSession_DataReceived; tcpSession.Error += new EventHandler <ErrorEventArgs>(tcpSession_Error); tcpSession.Connect(); }
public NcsMain(string ip, int port, Form1 form) { NcsTemplateBuffer.SetTempBuffer(); tcpSession = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse(ip), port)); tcpSession.Connected += tcpSession_Connected; tcpSession.Closed += tcpSession_Closed; tcpSession.DataReceived += tcpSession_DataReceived; tcpSession.Error += new EventHandler <ErrorEventArgs>(tcpSession_Error); tcpSession.Connect(); }
private AsyncTcpSession WSClient_ReConnect(EndPoint remorePoint) { //行情重连,要清空内存 var wsClient = new AsyncTcpSession(); wsClient.Connected += new EventHandler(WSClient__Opened); wsClient.Closed += new EventHandler(WSClient__Closed); wsClient.Error += new EventHandler <ErrorEventArgs>(WSClient__Error); wsClient.DataReceived += new EventHandler <DataEventArgs>(WSClient_DataReceived); wsClient.ReceiveBufferSize = 1024 * 64 + 2; wsClient.Connect(ipp); return(wsClient); }
/// <summary> /// 初始化 socket client /// </summary> /// <param name="config"></param> /// <returns></returns> public bool Init(JObject config) { try { // get local ip address foreach (IPAddress _ipaddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (_ipaddress.AddressFamily.ToString() == "InterNetwork") { nlogger.Trace("get the local ip address: " + _ipaddress.ToString()); ip = _ipaddress.ToString(); } } if (config.ContainsKey("IP")) { ip = (string)config["IP"]; } if (config.ContainsKey("Port")) { port = (int)config["Port"]; } _appClient.Connect(new IPEndPoint(IPAddress.Parse(ip), port)); _appClient.Connected += _appClient_Connected; _appClient.DataReceived += _appClient_DataReceived; _appClient.Closed += _appClient_Closed; } catch (Exception ex) { nlogger.Error("error with the socket client: " + ex.Message); return(false); } return(true); }
public static void RequestConnect(int countConnect) { lock (_tcpSession) { for (int i = 0; i < countConnect; i++) { AsyncTcpSession socket = new AsyncTcpSession(); _tcpSession.Add(socket); socket.Connected += tcpSession_Connected; socket.Closed += tcpSession_Closed; socket.DataReceived += tcpSession_DataReceived; socket.Connect(iPEndPoint); } } }
public bool Start() { lock (LockObj_IsConnection) { if (IsConnection) { return(true); } _clientSocket = new AsyncTcpSession(); RegistrationSocketEvent(_clientSocket); var ipEndPoint = new IPEndPoint(this.IpAddress, this.Port); _clientSocket.Connect(ipEndPoint); return(true); } }
private void reconnectToSuperSocket() { if (ClientSession == null) { this.ClientSession = new AsyncTcpSession(new IPEndPoint(LocalIPAddress(), RemoteSuperSocketPort), bufferSize); ClientSession.Connected += ClientSession_Connected; I($"Create Dectector Connection: IP:{LocalIPAddress().ToString()} port:{RemoteSuperSocketPort}"); ClientSession.Error += ClientSession_Error; ClientSession.DataReceived += ClientSession_DataReceived; timer = new Timer(); timer.Elapsed += Timer_Elapsed; timer.Interval = Interval * 1000; timer.Enabled = true; } if (!ClientSession.IsConnected) { ClientSession.Connect(); } }
static void Main(string[] args) { Console.WriteLine("DataReceived Count : {0}", count); Console.WriteLine("DataReceived Length : {0}", length); Console.WriteLine(); Console.WriteLine("Ping :"); Console.CursorVisible = false; NcsTemplateBuffer.SetTempBuffer(); tcpSession = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 65535)); tcpSession.Connected += tcpSession_Connected; tcpSession.Closed += tcpSession_Closed; tcpSession.DataReceived += tcpSession_DataReceived; tcpSession.Error += new EventHandler <ErrorEventArgs>(tcpSession_Error); tcpSession.Connect(); while (Console.ReadLine() != "q") { } }
internal void ConnectTarget(EndPoint remoteEndPoint, Action <ProxySession, TcpClientSession> connectedAction) { m_ConnectedAction = connectedAction; var targetSession = new AsyncTcpSession(remoteEndPoint); targetSession.ReceiveBufferSize = 2000000; targetSession.Connected += targetSession_Connected; targetSession.Closed += targetSession_Closed; targetSession.DataReceived += targetSession_DataReceived; targetSession.Error += targetSession_Error; var buffer = AppServer.RequestProxyBuffer(); if (buffer.Array == null) { this.Close(CloseReason.ServerClosing); return; } m_BufferSegment = buffer; targetSession.Connect(); }
/// <summary> /// Open按钮单击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Btn_open_Click(object sender, RoutedEventArgs e) { ip = tb_ip.Text; port = tb_port.Text; try { tcpClient = new AsyncTcpSession(); tcpClient.ReceiveBufferSize = 800 * 1024; tcpClient.Connect(new IPEndPoint(IPAddress.Parse(ip), int.Parse(port))); } catch (Exception error) { AddMessage("[Error] > " + error.Message); CloseState(); Log.Error("[Error] > " + error.Message); } tcpClient.DataReceived += TcpClient_DataReceived; tcpClient.Error += TcpClient_Error; tcpClient.Closed += TcpClient_Closed; tcpClient.Connected += TcpClient_Connected; }
private void OpenTcpThread(object arg) { try { int channelNumber = (int)arg; int index = 0; while (index < channelNumber) { try { //首先关闭当前的连接 if (tcpClient.IsConnected) { tcpClient.Close(); GlobalDataInterface.CommportConnectFlag = false; } else { GlobalDataInterface.CommportConnectFlag = false; } int SelId = m_ChanelIDList[index]; int m_InnerQualitySubsysindex = Commonfunction.GetSubsysIndex(SelId); //子系统索引 int m_InnerQualityChannelIndex = Commonfunction.GetChannelIndex(SelId); //子系统通道 int dataIndex = m_InnerQualitySubsysindex * ConstPreDefine.MAX_CHANNEL_NUM + m_InnerQualityChannelIndex; m_TcpChannelIndex = dataIndex; //当前选择的TCP通道索引 string ip = ConstPreDefine.LC_IP_ADDR_TEMPLATE + (dataIndex + 101); #region 网络Ping验证 Ping m_ping = new Ping(); PingReply pingReply = m_ping.Send(ip, 500); if (pingReply.Status != IPStatus.Success) { index++; continue; } //网络不通 #endregion tcpClient.Connect(new IPEndPoint(IPAddress.Parse(ip), ConstPreDefine.LC_PORT_NUM)); //建立index+1的通道连接 Thread.Sleep(500); if (GlobalDataInterface.CommportConnectFlag) { MessageDataSend(ConstPreDefine.SBC_INFO_REQ); //请求光谱仪指令 } Thread.Sleep(1000); //最后关闭当前的连接(仅在有需要时才打开连接) if (tcpClient.IsConnected) { tcpClient.Close(); GlobalDataInterface.CommportConnectFlag = false; } else { GlobalDataInterface.CommportConnectFlag = false; } } catch (Exception ex) { Trace.WriteLine("ProjectSetForm中函数OpenTcpThread的while循环出错,index=" + index.ToString() + ex); #if REALEASE GlobalDataInterface.WriteErrorInfo("ProjectSetForm中函数OpenTcpThread的while循环出错,index=" + index.ToString() + ex); #endif } index++; } } catch (Exception ex) { Trace.WriteLine("ProjectSetForm中函数OpenTcpThread出错" + ex); #if REALEASE GlobalDataInterface.WriteErrorInfo("ProjectSetForm中函数OpenTcpThread出错" + ex); #endif } }
public void Setup() { BaseClient.Connect(new IPEndPoint(IPAddress.Parse(SocketStatus.GetIpAddress), 6865)); }
private void buttonConnectServer_Click(object sender, EventArgs e) { tcpSession.Connect(new IPEndPoint(IPAddress.Parse(textBoxIpAddress.Text), Convert.ToInt32(textBoxPort.Text))); }