protected override IConnectFuture Connect(Int32 port, IoHandler handler) { IoConnector connector = new AsyncSocketConnector(); connector.Handler = handler; return(connector.Connect(new IPEndPoint(IPAddress.Loopback, port))); }
private void KeepAliveFilterForIdleStatus(IdleStatus status) { using (AsyncSocketConnector connector = new AsyncSocketConnector()) { KeepAliveFilter filter = new KeepAliveFilter(new ClientFactory(), status, KeepAliveRequestTimeoutHandler.Exception, INTERVAL, TIMEOUT); filter.ForwardEvent = true; connector.FilterChain.AddLast("keep-alive", filter); Boolean gotException = false; connector.ExceptionCaught += (s, e) => { // A KeepAliveRequestTimeoutException will be thrown if no keep-alive response is received. Console.WriteLine(e.Exception); gotException = true; }; IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, port)).Await(); IoSession session = future.Session; Assert.IsNotNull(session); Thread.Sleep((INTERVAL + TIMEOUT + 3) * 1000); Assert.IsFalse(gotException, "got an exception on the client"); session.Close(true); } }
/// <summary> /// 初始化Socket服务 /// </summary> private void InitializeSocketService() { var connector = new AsyncSocketConnector(); connector.SessionConfig.ReadBufferSize = 2048; connector.SessionConfig.SetIdleTime(IdleStatus.BothIdle, 10); // 添加过滤器 var demuxingCodec = new DemuxingProtocolCodecFactory(); demuxingCodec.AddMessageEncoder<IClientInfo, ClientInfoProtocolEncoder>(); demuxingCodec.AddMessageEncoder<IList<IFileHash>, FileHashesProtocolEncoder>(); demuxingCodec.AddMessageDecoder<TransferingZipFileProtocolDecoder>(); demuxingCodec.AddMessageDecoder<UpdateFileCollectionProtocolDecoder>(); connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(demuxingCodec)); connector.FilterChain.AddLast("logger", new LoggingFilter()); // 添加业务逻辑 var demuxingHandler = new DemuxingIoHandler(); demuxingHandler.AddReceivedMessageHandler(new UpdateFileCollectionMessageHandler((s, o) => { //客户端收到服务器发来的更新文件名列表后,显示更新信息,分析本地文件、计算本地文件Hash,并发给服务器 //通知ViewModel更新UpdateInfo属性 var aggregator = ServiceLocator.Current.GetInstance<IEventAggregator>(); aggregator.GetEvent<UpdateFileCollectionEvent>().Publish(o); //获取目标应用路径的绝对路径 var appFolder = Settings.Default.TargetApplicationFolder; appFolder = Path.GetFullPath(appFolder); if (!Directory.Exists(appFolder)) { // TODO 目标目录不存在 //MessageBox.Show("目标目录不存在"); } //计算Hash var fileHashes = new List<IFileHash>(); foreach (var file in o) { var filePath = Path.Combine(appFolder, file); var fileHash = new FileHash { FileName = file }; if (File.Exists(filePath)) { fileHash.HashBytes = FileHashHelper.ComputeFileHash(filePath); } fileHashes.Add(fileHash); } s.Write(fileHashes); })); demuxingHandler.AddReceivedMessageHandler(new TransferingZipFileMessageHandler((s, o) => { // TODO 客户端收到服务器发来的更新文件压缩包后,停止正在运行的应用程序,备份旧文件,覆盖新文件 })); connector.Handler = demuxingHandler; Container.RegisterInstance<IoConnector>(connector, new ContainerControlledLifetimeManager()); }
public void UncaughtExceptionTest() { var are = new AutoResetEvent(false); var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001); var connector = new AsyncSocketConnector(); connector.FilterChain.AddLast("fireExceptiojn", new FireExceptionFilter(are)); connector.FilterChain.AddLast("exceptionCounter", ObjectHost.Host.Resolve<ExceptionCounterFilter>()); connector.FilterChain.AddLast("logger", new LoggingFilter()); connector.SessionCreated += (s, e) => { e.Session.SetAttributeIfAbsent(KeyName.SESSION_ERROR_COUNTER, 0); }; var future = connector.Connect(endPoint); future.Await(); var session = future.Session; var guid = Guid.NewGuid().ToByteArray(); var serverIdentifier = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("ctppv5_command_server")).ToHex(); var buffer = ByteBufferAllocator.Instance.Allocate(48); buffer.AutoExpand = true; buffer.PutInt32(49); buffer.Put(1); buffer.PutInt16(1); buffer.Put(ErrorCode.NoError.ToByte()); buffer.Put(MessageType.Command.ToByte()); buffer.Put(Guid.NewGuid().ToByteArray()); buffer.Put(guid); buffer.Put((MessageFilterType.Checksum).ToByte()); buffer.Put(new byte[] { 0, 0 }); buffer.Put(SerializeMode.None.ToByte()); buffer.Position = 0; var header = buffer.GetArray(45); buffer.Put(BitConverter.GetBytes(Crc32.CalculateDigest(header, (uint)0, (uint)(header.Length)))); buffer.Position = buffer.Position - 1; // make crc error buffer.Put(4); for (int i = 0; i < 6; i++) { buffer.Flip(); session.Write(buffer); are.WaitOne(); } while (true) { if (session.Connected) Thread.Sleep(200); else break; } }
public void ServerStartUpTest() { var bootstrap = new ServerBootstrap(EndPointDispatcher.GetRandomPort()); Assert.IsTrue(bootstrap.StartUp()); var connector = new AsyncSocketConnector(); var future = connector.Connect(bootstrap.EndPoint); Assert.IsTrue(future.Await(500)); System.Threading.Thread.Sleep(500); Assert.AreEqual(1, bootstrap.Server.ManagedSessions.Count); Assert.IsTrue(future.Connected); Assert.IsNotNull(future.Session); bootstrap.Server.Dispose(); connector.Dispose(); }
static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine(typeof(Program).FullName + " <hostname> <port>"); return; } // Create TCP/IP connector. AsyncSocketConnector connector = new AsyncSocketConnector(); // Set connect timeout. connector.ConnectTimeoutInMillis = 30 * 1000L; // Set reader idle time to 10 seconds. // sessionIdle(...) method will be invoked when no data is read // for 10 seconds. connector.SessionOpened += (s, e) => e.Session.Config.SetIdleTime(IdleStatus.ReaderIdle, 10); // Print out total number of bytes read from the remote peer. connector.SessionClosed += (s, e) => Console.WriteLine("Total " + e.Session.ReadBytes + " byte(s)"); connector.SessionIdle += (s, e) => { if (e.IdleStatus == IdleStatus.ReaderIdle) e.Session.Close(true); }; connector.MessageReceived += (s, e) => { IoBuffer buf = (IoBuffer)e.Message; while (buf.HasRemaining) { Console.Write((Char)buf.Get()); } }; // Start communication. IConnectFuture cf = connector.Connect(new IPEndPoint(Dns.GetHostEntry(args[0]).AddressList[3], Int32.Parse(args[1]))); // Wait for the connection attempt to be finished. cf.Await(); cf.Session.CloseFuture.Await(); connector.Dispose(); }
/// <summary> /// OpenMinaSocket /// Open a socket with the parameter /// specified in the constructor /// </summary> private void OpenMinaSocket() { Connector = new AsyncSocketConnector(); Connector.FilterChain.AddLast("logger", new LoggingFilter()); Connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Encoding.UTF8))); Connector.SessionOpened += (s, e) => { e.Session.Write("open"); CallDUpdateText(String.Format("SessionOpened")); }; Connector.MessageReceived += (s, e) => { String IncomingStringBuffer = e.Message.ToString(); CallDUpdateText(String.Format("MessageReceived {0}", IncomingStringBuffer)); }; while (!cancelConnetionRetry) { try { IConnectFuture Future = Connector.Connect(new IPEndPoint(_serverIPAddress, _port)); Future.Await(); Session = Future.Session; CallDUpdateText(String.Format("Connection to {0}:{1} established", _serverIPAddress.ToString(), _port)); break; } catch (Exception ex) { CallDUpdateText(String.Format("Exception in OpenMinaSocket {0}", ex.Message)); Thread.Sleep(500); } } }
private static void ClientConnect() { using (var client = new AsyncSocketConnector()) using (var ready = new System.Threading.ManualResetEventSlim(false)) { client.FilterChain.AddLast("ssl", new SslFilter("TempCert", null)); client.FilterChain.AddLast("text", new ProtocolCodecFilter(new TextLineCodecFactory())); client.MessageReceived += (s, e) => { Debug.WriteLine("Client got: " + e.Message); ready.Set(); }; var session = client.Connect(new IPEndPoint(IPAddress.Loopback, port)).Await().Session; Debug.WriteLine("Client sending: hello"); session.Write("hello "); Debug.WriteLine("Client sending: send"); session.Write("send"); ready.Wait(3000); Assert.IsTrue(ready.IsSet); ready.Reset(); Assert.IsFalse(ready.IsSet); Debug.WriteLine("Client sending: hello"); session.Write(IoBuffer.Wrap(Encoding.UTF8.GetBytes("hello \n"))); Debug.WriteLine("Client sending: send"); session.Write(IoBuffer.Wrap(Encoding.UTF8.GetBytes("send\n"))); ready.Wait(3000); Assert.IsTrue(ready.IsSet); session.Close(true); } }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Please specify the list of any integers"); return; } // prepare values to sum up int[] values = new int[args.Length]; for (int i = 0; i < args.Length; i++) { values[i] = Int32.Parse(args[i]); } AsyncSocketConnector connector = new AsyncSocketConnector(); // Configure the service. connector.ConnectTimeoutInMillis = CONNECT_TIMEOUT; if (USE_CUSTOM_CODEC) { connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false))); } else { connector.FilterChain.AddLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); } connector.FilterChain.AddLast("logger", new LoggingFilter()); connector.SessionOpened += (s, e) => { // send summation requests for (int i = 0; i < values.Length; i++) { AddMessage m = new AddMessage(); m.Sequence = i; m.Value = values[i]; e.Session.Write(m); } }; connector.ExceptionCaught += (s, e) => { Console.WriteLine(e.Exception); e.Session.Close(true); }; connector.MessageReceived += (s, e) => { // server only sends ResultMessage. otherwise, we will have to identify // its type using instanceof operator. ResultMessage rm = (ResultMessage)e.Message; if (rm.OK) { // server returned OK code. // if received the result message which has the last sequence // number, // it is time to disconnect. if (rm.Sequence == values.Length - 1) { // print the sum and disconnect. Console.WriteLine("The sum: " + rm.Value); e.Session.Close(true); } } else { // seever returned error code because of overflow, etc. Console.WriteLine("Server error, disconnecting..."); e.Session.Close(true); } }; IoSession session; while (true) { try { IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, PORT)); future.Await(); session = future.Session; break; } catch (Exception ex) { Console.WriteLine(ex); Thread.Sleep(3000); } } // wait until the summation is done session.CloseFuture.Await(); Console.WriteLine("Press any key to exit"); Console.Read(); }
protected override IConnectFuture Connect(Int32 port, IoHandler handler) { IoConnector connector = new AsyncSocketConnector(); connector.Handler = handler; return connector.Connect(new IPEndPoint(IPAddress.Loopback, port)); }