static void Main(string[] args) { try { int responseCount = 0; System.Console.WriteLine("Please enter the IP Address of the server, or leave blank for 192.168.1.128: "); var ipAddress = System.Console.ReadLine(); if (string.IsNullOrEmpty(ipAddress)) { ipAddress = "192.168.1.128"; } var client = new AsyncTcpClient(); client.DataReceived += (sender, e) => System.Console.WriteLine("{0}: Received from server something of size: {1}", ++responseCount, e.Value.Length); client.Connect(IPAddress.Parse(ipAddress), 8080); System.Console.WriteLine("Connected!"); System.Console.ReadKey(); } catch (Exception ex) { System.Console.WriteLine(ex.Message); } }
private void Button_Click(object sender, RoutedEventArgs e) { tcpClient = new AsyncTcpClient(IPAddress.Parse(Settings.IpAddress), Settings.Port); tcpClient.Encoding = Encoding.UTF8; tcpClient.DatagramReceived += TcpClient_DatagramReceived; tcpClient.PropertyChanged += TcpClient_PropertyChanged; tcpClient.ServerDisconnected += TcpClient_ServerDisconnected; tcpClient.ServerExceptionOccurred += TcpClient_ServerExceptionOccurred; switch (Settings.DeviceType) { case DeviceType.W6: emulator = new W6Emulator(tcpClient); break; case DeviceType.V6: emulator = new V6Emulator(tcpClient); break; case DeviceType.CA310: throw new NotImplementedException("ca310 emulator is not implemented."); default: break; } if (emulator == null) { return; } ((TCPCOMMODE)emulator).MessageSent += W6Emulator_MessageSent; tcpClient.Connect(); }
static void Main(string[] args) { LogFactory.Assign(new ConsoleLogFactory()); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); IPEndPoint localEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9998); // 测试用,可以不指定由系统选择端口 client = new AsyncTcpClient(remoteEP, localEP); client.Encoding = Encoding.UTF8; client.ServerExceptionOccurred += new EventHandler <TcpServerExceptionOccurredEventArgs>(client_ServerExceptionOccurred); client.ServerConnected += new EventHandler <TcpServerConnectedEventArgs>(client_ServerConnected); client.ServerDisconnected += new EventHandler <TcpServerDisconnectedEventArgs>(client_ServerDisconnected); client.PlaintextReceived += new EventHandler <TcpDatagramReceivedEventArgs <string> >(client_PlaintextReceived); client.Connect(); Console.WriteLine("TCP client has connected to server."); Console.WriteLine("Type something to send to server..."); while (true) { try { string text = Console.ReadLine(); client.Send(text); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
/// <summary> /// 初始化网络并连接 /// </summary> public static void InitialNetWorkClient() { //TCPClient初始化 ControllerServer = new AsyncTcpClient(Parameters.TcpServerHost, Parameters.TcpServerPort); //异常事件 ControllerServer.ServerExceptionOccurred += new EventHandler <TcpServerExceptionOccurredEventArgs>(ControllerServer_ServerExceptionOccurred); //已连接到服务器 ControllerServer.ServerConnected += new EventHandler <TcpServerConnectedEventArgs>(ControllerServer_ServerConnected); //与服务器断开连接 ControllerServer.ServerDisconnected += new EventHandler <TcpServerDisconnectedEventArgs>(ControllerServer_ServerDisconnected); //接收到服务器的数据(字符串) ControllerServer.PlaintextReceived += new EventHandler <TcpDatagramReceivedEventArgs <string> >(ControllerServer_PlaintextReceived); //接收到服务器的数据(字节流) ControllerServer.DatagramReceived += new EventHandler <TcpDatagramReceivedEventArgs <byte[]> >(ControllerServer_DatagramReceived); //连接服务器 ControllerServer.Connect(); }
private void TcpClient_ServerDisconnected(object sender, TcpServerDisconnectedEventArgs e) { if (tcpClient != null && !tcpClient.Connected) { WriteLog("连接已断开,重新连接......"); tcpClient.Connect(); } }
/// <summary> /// 初始化TCP Client /// </summary> private void InitNetWork() { client = new AsyncTcpClient(IPAddress.Parse(ConfigurationManager.AppSettings["SignatureDeviceIP"]), Constants.SignatureDeviceIPPort); client.Connect(); client.ServerConnected += new EventHandler <TcpServerConnectedEventArgs>(Connected); client.ServerDisconnected += new EventHandler <TcpServerDisconnectedEventArgs>(Disconnected); client.PlaintextReceived += new EventHandler <TcpDatagramReceivedEventArgs <string> >(PlainTextReceived); client.DatagramReceived += new EventHandler <TcpDatagramReceivedEventArgs <byte[]> >(DatagramReceived); }
/// <summary> /// 初始化TCP Client /// </summary> private void InitNetWork() { client = new AsyncTcpClient(IPAddress.Parse("192.168.31.33"), Constants.SignatureDeviceIPPort); client.Connect(); client.ServerConnected += new EventHandler <TcpServerConnectedEventArgs>(Connected); client.ServerDisconnected += new EventHandler <TcpServerDisconnectedEventArgs>(Disconnected); client.PlaintextReceived += new EventHandler <TcpDatagramReceivedEventArgs <string> >(PlainTextReceived); client.DatagramReceived += new EventHandler <TcpDatagramReceivedEventArgs <byte[]> >(DatagramReceived); }
private void connectBtn_Click(object sender, EventArgs e) { bool blnText1 = false;//检查端口是否合法 blnText1 = IsNumberic(portTb.Text); //连接服务端 if (this.IsPort() && blnText1) { String ip = ipTb.Text; int port = Convert.ToInt32(portTb.Text); client = new AsyncTcpClient(new IPEndPoint(IPAddress.Parse(ip), port)); client.ServerDisconnected += new EventHandler <TcpServerDisconnectedEventArgs>(client_ServerDisconnected); client.PlaintextReceived += new EventHandler <TcpDatagramReceivedEventArgs <string> >(client_PlaintextReceived); client.ServerConnected += new EventHandler <TcpServerConnectedEventArgs>(client_ServerConnected); if (connectBtn.Text == "连接")/*第一次连接*/ { try { client.Connect(); isConnect = true; } catch (Exception c) { MessageBox.Show(c.ToString() + "不符合IP格式"); receiveTb.AppendText(Line++ + " 未连接上了服务器:" + ip + "\n"); } } else if (connectBtn.Text == "重连")/*重新进行连接*/ { try { client.Close(); client.Connect(); isConnect = true; receiveTb.AppendText(Line++ + " 成功与服务器重连" + ip + "\n"); } catch (Exception c) { MessageBox.Show(c.ToString() + "不符合IP格式"); isConnect = false; } } } }
public void Run() { Status = RunStatus.Init; if (Setting.Interval < 50) { Setting.Interval = 50; } mCount = 0; mClients = new List <BeetleX.Clients.AsyncTcpClient>(Setting.Connection); for (int i = 0; i <= 50000 * IPAddress.Length; i++) { string ip = IPAddress[i % IPAddress.Length]; var port = GetPortResource(ip); AsyncTcpClient client = BeetleX.SocketFactory.CreateClient <AsyncTcpClient>(Server.Host, Server.Port); client.LocalEndPoint = new IPEndPoint(System.Net.IPAddress.Parse(ip), port.Next()); if (client.Connect()) { client.DataReceive = OnClientReceive; ClientToken token = new ClientToken(); client.Token = token; mClients.Add(client); mCount++; if (Setting.Mode == "Interval") { token.Node = new LinkedListNode <AsyncTcpClient>(client); mLinks[mCount % mLinks.Count].AddFirst(token.Node); } if (mClients.Count >= Setting.Connection) { Task.Run(() => BeginSend()); return; } } else { SocketException se = client.LastError as SocketException; if (se != null) { if (se.ErrorCode == (int)SocketError.AddressNotAvailable || se.ErrorCode == (int)SocketError.ConnectionRefused || se.ErrorCode == (int)SocketError.NetworkUnreachable) { Stop(); throw se; } } } } if (mClients.Count > 0) { Task.Run(() => BeginSend()); } return; }
/// <summary> /// 连接到服务端 /// </summary> public void ConnectToService() { client = new AsyncTcpClient(IPAddress.Parse(IP), Port); client.ServerConnected += Client_ServerConnected; //连接成功 client.PlaintextReceived += Client_PlaintextReceived; //文本接收 client.DatagramReceived += Client_DatagramReceived; //字节接收 client.ServerDisconnected += Client_ServerDisconnected; //断开连接 client.ServerExceptionOccurred += Client_ServerExceptionOccurred; // client.Connect(); }
public void InitializeSocket(string ip, int port, bool isDomain = false) { mStructCopyer = new StructCopyer(); mAsyncTcpClient = new AsyncTcpClient(ip, port, isDomain); mAsyncTcpClient.ConnectedEventArgs += OnConnectedEventArgs; mAsyncTcpClient.DisconnectedEventArgs += OnDisconnectedEventArgs; mAsyncTcpClient.ExceptionEventArgs += OnExceptionEventArgs; mAsyncTcpClient.DataPacketReceived += OnDataPacketReceived; mAsyncTcpClient.Connect(); }
public void Connect() { if (IsConnected) { return; } lock (mLockConnect) { if (IsConnected) { return; } mWScompletionSource = new TaskCompletionSource <bool>(); if (mNetClient == null) { string protocol = Host.Scheme.ToLower(); if (!(protocol == "ws" || protocol == "wss")) { OnConnectResponse(new BXException("protocol error! host must [ws|wss]//host:port"), null); mWScompletionSource.Task.Wait(); } WSPacket wSPacket = new WSPacket { WSClient = this }; if (Host.Scheme.ToLower() == "wss") { mNetClient = SocketFactory.CreateSslClient <AsyncTcpClient>(wSPacket, Host.Host, Host.Port, SSLAuthenticateName); mNetClient.CertificateValidationCallback = CertificateValidationCallback; } else { mNetClient = SocketFactory.CreateClient <AsyncTcpClient>(wSPacket, Host.Host, Host.Port); } mNetClient.LittleEndian = false; mNetClient.PacketReceive = OnPacketCompleted; mNetClient.ClientError = OnClientError; } mDataFrames = new System.Collections.Concurrent.ConcurrentQueue <object>(); bool isNew; if (mNetClient.Connect(out isNew)) { OnWriteConnect(); } else { OnConnectResponse(mNetClient.LastError, null); } mWScompletionSource.Task.Wait(5000); if (!OnWSConnected) { throw new TimeoutException($"Connect {Host} websocket server timeout!"); } } }
public void Start() { try { tcpClient = new AsyncTcpClient(new IPEndPoint(IPAddress.Parse(this._ip), this._port), _message, new AlgorithmCodecBuilder()); tcpClient.Connect().Wait(); } catch (Exception ex) { } }
public void Init(string ip, int port) { try { _ip = ip; _port = port; tcpClient = new AsyncTcpClient(new IPEndPoint(IPAddress.Parse(_ip), _port), new ServerCommunicationMessage(), new ServerCommunicationCodecBuilder()); tcpClient?.Connect().Wait(); } catch (Exception ex) { } }
private void Connect() { if (IsConnected) { return; } lock (mLockConnect) { if (IsConnected) { return; } mWScompletionSource = new TaskCompletionSource <bool>(); if (mNetClient == null) { string protocol = UriHost.Scheme.ToLower(); if (!(protocol == "ws" || protocol == "wss")) { OnConnectResponse(new BXException("protocol error! host must [ws|wss]//host:port"), null); mWScompletionSource.Task.Wait(); } WSPacket wSPacket = new WSPacket { WSClient = this }; if (UriHost.Scheme.ToLower() == "wss") { mNetClient = SocketFactory.CreateSslClient <AsyncTcpClient>(wSPacket, UriHost.Host, UriHost.Port, SSLAuthenticateName); } else { mNetClient = SocketFactory.CreateClient <AsyncTcpClient>(wSPacket, UriHost.Host, UriHost.Port); } mNetClient.LittleEndian = false; mNetClient.PacketReceive = OnPacketCompleted; mNetClient.ClientError = OnClientError; } mDataFrames = new System.Collections.Concurrent.ConcurrentQueue <AgentDataFrame>(); bool isnew; if (mNetClient.Connect(out isnew)) { OnWriteConnect(); } else { OnConnectResponse(mNetClient.LastError, null); } mWScompletionSource.Task.Wait(); } }
public void Send(RPCPacket request, AsyncTcpClient client = null) { client = client ?? GetClient(); bool isnew; if (client.Connect(out isnew)) { client.Send(request); System.Threading.Interlocked.Increment(ref mRequests); } else { throw client.LastError; } }
protected void ConnectServer(string remoteHostName, int remotePort) { if (tcpClient != null) { return; } tcpClient = new AsyncTcpClient(remoteHostName, remotePort); tcpClient.Encoding = Encoding.UTF8; tcpClient.ServerConnected += TcpClient_ServerConnected; tcpClient.ServerDisconnected += TcpClient_ServerDisconnected; tcpClient.ServerExceptionOccurred += TcpClient_ServerExceptionOccurred; tcpClient.DatagramReceived += TcpClient_DatagramReceived; tcpClient.Connect(); }
private void Window_Loaded(object sender, RoutedEventArgs e) { MyLogger myLogger = new MyLogger(); BeginEndFilter receiveDataFilter = new BeginEndFilter(); asyncTcpClient = new AsyncTcpClient( new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 4000), receiveDataFilter, Encoding.UTF8, myLogger); asyncTcpClient.EnableKeepAlive = true; asyncTcpClient.ServerConnected += AsyncTcpClient_ServerConnected; asyncTcpClient.ServerDisconnected += AsyncTcpClient_ServerDisconnected; asyncTcpClient.NewRequestReceived += AsyncTcpClient_NewRequestReceived; asyncTcpClient.Error += AsyncTcpClient_Error; asyncTcpClient.Connect(); }
private void ReconnectBtn_Click(object sender, EventArgs e) { try { String ip = ipTb.Text; int port = Convert.ToInt32(portTb.Text); client.Close(); client.Connect(); isConnect = true; } catch (Exception c) { MessageBox.Show(c.ToString() + "不符合IP格式"); isConnect = false; } }
private void IntializeTcpConnection() { //IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); // 测试用 //IPEndPoint localEP = new IPEndPoint(IPAddress.Parse("192.168.8.131"), 9998); // 测试用,可以不指定由系统选择端口 IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.8.1"), 2001); _tcpClient = new AsyncTcpClient(remoteEP); _tcpClient.Encoding = Encoding.UTF8; _tcpClient.ServerExceptionOccurred += new EventHandler <TcpServerExceptionOccurredEventArgs>(OnTcpServerExceptionOccurred); _tcpClient.ServerConnected += new EventHandler <TcpServerConnectedEventArgs>(OnTcpServerConnected); _tcpClient.ServerDisconnected += new EventHandler <TcpServerDisconnectedEventArgs>(OnTcpServerDisconnected); _tcpClient.PlaintextReceived += new EventHandler <TcpDatagramReceivedEventArgs <string> >(OnTcpPlaintextReceived); Console.WriteLine("TCP client is connecting to server."); _tcpClient.Connect(); }
private void btnLogin_Click(object sender, RoutedEventArgs e) { client = new AsyncTcpClient(txtIpAddress.Text, remotePort); client.Encoding = Encoding.UTF8; //当收到服务器端文本数据的时候 client.PlaintextReceived += new EventHandler<ReceivedEventArgs<string>>(client_PlaintextReceived); client.Connect(); System.Threading.Thread.Sleep(1000); if (client.Connected) { btnExit.IsEnabled = true; btnLogin.IsEnabled = false; timer_current.Start(); lblStatus.Content = "已成功链接到服务器。"; btnUserLogin.IsEnabled = true; } }
/// <summary> /// 检查期间就开启服务 /// </summary> Task IZeroDiscover.Discovery() { if (TcpOption.Instance.Client == null || TcpOption.Instance.Client.Address.IsBlank() || TcpOption.Instance.Client.Port <= 1024 || TcpOption.Instance.Client.Port >= short.MaxValue) { return(Task.CompletedTask); } client = SocketFactory.CreateClient <AsyncTcpClient>(TcpOption.Instance.Client.Address, TcpOption.Instance.Client.Port); client.DataReceive = EventClientReceive; client.ClientError = EventClientError; client.Disconnected = Disconnected; client.Connected = Connected; client.Connect(out _); DoStart(); RecordLog(LogLevel.Information, $"{Name}已开启"); return(Task.CompletedTask); }
/// <summary> /// 选中相应区号的密集架 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cbxGroupNo_SelectedIndexChanged(object sender, EventArgs e) { Rack rack = null; int groupNo = Convert.ToInt16(cbxGroupNo.Text); try { // 获取本区列信息 rack = GetRackInfo(groupNo); } catch (Exception ex) { MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //devMonitor.MonitorDevList.Clear();//清除之前的监控列表 devMonitor.MonitorDevDic.Clear(); if (tcpClient.Connected) { // 关闭当前连接 tcpClient.Close(); } // 当前区的IP地址和端口号 IPAddress remoteIP = IPAddress.Parse(rack.DevIP); int remotePort = rack.DevPort; // 异步连接 tcpClient.Connect(remoteIP, remotePort); // 堵塞等待3秒 if (connectDone.WaitOne(3000, false) == false) { // 超时,连接服务器失败 tcpClient.Close(); string info = string.Format("无法连接{0}区服务器:IP地址{1} 端口号{2}", cbxGroupNo.Text, remoteIP.ToString(), remotePort); lsbInfoBoard.Items.Add(info); return; } // 读取环境信息 UpdateEnvironmentInfo(); }
public Task <RPCPacket> SendWait(RPCPacket request, AsyncTcpClient client, Type[] resultType = null) { client = client ?? GetClient(); bool isnew; if (client.Connect(out isnew)) { var result = mAwaiterFactory.Create(request, resultType, TimeOut); request.ID = result.Item1; client.Send(request); System.Threading.Interlocked.Increment(ref mRequests); return(result.Item2.Task); } else { throw client.LastError; } }
/// <summary>使用当前用户加入会议</summary> public void Connect() { try { Console.WriteLine("-> client.connect ->"); client = new AsyncTcpClient(SystemSetting.Instance.IP , Int32.Parse(SystemSetting.Instance.Port)); client.DatagramReceived += client_DatagramReceived; client.ServerConnected += client_Connected; client.ServerDisconnected += client_Disconnected; client.ServerException += client_ServerException; client.Connect(); } catch (Exception ex) { Console.WriteLine(ex.Message); MessageBox.Show("服务端IP地址或端口输入错误,请核实后重新连接!"); } }
private Task ConnectServer() { _connecTask = Task.Run(() => { var ip = tbIP.Text; var port = tbPort.Text.ToInt(); var con = tbConCount.Text.ToInt(); for (int i = 0; i < con; i++) { if (!_loopConStatus) { break; } AsyncTcpClient client = SocketFactory.CreateClient <AsyncTcpClient>(ip, port); client.ClientError = (o, e) => { ControlIncrement(lbErrorCount); ControlAssign(lbErrorMsg, e.Message); }; client.Receive = (o, e) => { string data = e.Stream.ToPipeStream().ReadToEnd(); ControlIncrement(lbReceiveDataCount); }; client.Connected = (c) => { ControlIncrement(lbClientCount); _clients.Add(client); }; client.Connect(); } ControlDelegate(btnPause, () => { if (!btnStart.Enabled) { btnPause.Enabled = true; } }); ControlDelegate(btnPause, () => { btnStop.Enabled = true; }); }); return(_connecTask); }
static void Main(string[] args) { AsyncTcpClient client = SocketFactory.CreateClient <AsyncTcpClient>("127.0.0.1", 9090); //AsyncTcpClient client = SocketFactory.CreateSslClient<AsyncTcpClient>("127.0.0.1", 9090, "localhost"); client.ClientError = (c, e) => { Write(string.Format("client error {0} {1}\r\n", e.Error, e.Message)); }; client.DataReceive = (o, e) => { string line = e.Stream.ToPipeStream().ReadLine(); Cmd cmd = ChatParse.Parse(line); Console.WriteLine(cmd.Text); }; while (true) { Write("login enter you name:"); string line = Console.ReadLine(); string cmd = ChatParse.CreateCommand(CmdType.LOGIN, line); client.Connect(); client.Stream.ToPipeStream().WriteLine(cmd); client.Stream.Flush(); while (true) { line = Console.ReadLine(); if (line == "quit") { client.DisConnect(); break; } cmd = ChatParse.CreateCommand(CmdType.SPEAK, line); client.Stream.ToPipeStream().WriteLine(cmd); client.Stream.Flush(); } } }
/// <summary> /// 连接服务器端 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ConnectClicked(object sender, RoutedEventArgs e) { var ip = tbIP.Text.Trim(); var port = tbPort.Text.Trim(); if (!string.IsNullOrEmpty(ip) && !string.IsNullOrEmpty(port)) { if (tcpClient == null) { try { tcpClient = new AsyncTcpClient(IPAddress.Parse(ip), int.Parse(port)); tcpClient.Connect(); tcpClient.DatagramReceived += client_DatagramReceived; lblStatus.Content = "已连接"; } catch (Exception ex) { throw new Exception(string.Format("创建客户端连接失败:{0}", ex.Message)); } } } }
// Start is called before the first frame update void Start() { m_NameTxt.text = "Connection:" + DateTime.Now.ToLongTimeString(); m_HeartBeat = false; m_LoginBtn.onClick.AddListener(OnLogin); m_StartHeartbeatBtn.onClick.AddListener(OnStartHeartbeat); m_StopHeartbeatBtn.onClick.AddListener(OnStopHeartbeat); m_CloseBtn.onClick.AddListener(OnClose); Thread t = new Thread(() => { m_TcpClient = new AsyncTcpClient(); m_TcpClient.OnDisconnected += OnDisconnect; //m_TcpClient.Connect("127.0.0.1", 88); //m_TcpClient.Connect("192.168.1.137", 88); m_TcpClient.Connect(m_ParentUILogic.m_TcpIP, m_ParentUILogic.m_TcpPort); }); t.Start(); }
// :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: private void connectTcp() { // is there a tcp connection to the vna? if (asyncTcpClient.connected == false) { // no... try { // create a new tcp client object asyncTcpClient = new AsyncTcpClient(); // connect to server asyncTcpClient.Connect(textBoxIP.Text, Convert.ToInt32(textBoxPort.Text)); // configure received data callback event handler asyncTcpClient.ProcessReceivedDataCallback += new AsyncTcpClient.CallbackEventHandler(receiveTcpData); // log the event appendToLogTextBox("Connected thru TCP/IP Socket"); } catch (Exception e) { // show exception error message MessageBox.Show("Please make sure the Socket Server is ON and the TCP/IP Port matches on the VNA software." + "\n\n" + e.Message, Program.programName, MessageBoxButtons.OK, MessageBoxIcon.Error); // log the event appendToLogTextBox("ERROR: Could Not Connect to the VNA thru TCP"); } // update vna panel ui updateControls(asyncTcpClient.connected); } }
private void Init() { client = SocketFactory.CreateClient <AsyncTcpClient>(host, 8800); client.DataReceive = (o, args) => { string line = args.Stream.ToPipeStream().ReadLine(); line = ChatModel.Util.StringUtil.GetGBString(line); Console.WriteLine(line); CmdInfo info = JsonSerializer.Deserialize <CmdInfo>(line); switch (info.Type) { case CmdType.Error: Console.WriteLine(info.GetDataRowText()); break; case CmdType.Login: user = info.As <User>(); Console.WriteLine($"欢迎[{user.Name}]登录系统"); break; case CmdType.SendMsg: ReceiveMsgInfo receiveMsgInfo = info.As <ReceiveMsgInfo>(); if (receiveMsgInfo != null) { Console.WriteLine($"[{receiveMsgInfo.From.Name}]:[{receiveMsgInfo.Msg}]"); } break; } }; client.Connected += (c) => { Console.WriteLine("已经连接到服务器"); }; client.Connect(); }