/// <summary> /// 等待服务停止 /// </summary> public virtual async Task StopAsync() { OnSubMessage?.Invoke("正在停止服务......", "重要"); await _bootstrapChannel.CloseAsync(); OnSubMessage?.Invoke("服务已停止", "重要"); }
private async Task StartAsync() { try { OnSubMessage?.Invoke($"正在连接{_clientConfig.Url}....", "重要"); ClientWebSocket = new ClientWebSocket(); var uri = new Uri(_clientConfig.Url); _cancellationToken = new CancellationToken(); await ClientWebSocket.ConnectAsync(uri, _cancellationToken); OnSubMessage?.Invoke("连接成功", "重要"); if (!_isListening) { StartListeningAsync(); } _isManualClose = false; OnConnectionSuccess?.Invoke(); _reconnectionNumber = 0; } catch (Exception exception) { await StopAsync(false); OnSubMessage?.Invoke("连接失败", "重要"); OnException?.Invoke(exception); OnConnectionFail?.Invoke(); } }
/// <summary> /// 开始监听 /// </summary> /// <returns></returns> private async void StartListeningAsync() { if (_isListening) { return; } _isListening = true; while (ClientWebSocket.State == WebSocketState.Open) { byte[] serverByteArray = new byte[655300000]; ArraySegment <byte> buffer = new ArraySegment <byte>(serverByteArray); WebSocketReceiveResult wsData; try { wsData = await ClientWebSocket.ReceiveAsync(buffer, _cancellationToken); if (wsData == null) { MateralDotNettyException materalDotNettyException = new MateralDotNettyException("未获取到服务器数据"); OnException?.Invoke(materalDotNettyException); } } catch (Exception exception) { if (_isManualClose) { return; } await StopAsync(false); OnSubMessage?.Invoke("与服务器断开连接", "重要"); OnException?.Invoke(exception); OnClose?.Invoke(); _isListening = false; continue; } try { string eventJson = GetEventJson(serverByteArray, wsData); try { await HandlerMessageAsync(eventJson); } catch (Exception exception) { OnSubMessage?.Invoke("处理事件出现错误", "重要"); OnSubMessage?.Invoke(eventJson, "重要"); OnException?.Invoke(exception); } } catch (Exception exception) { OnSubMessage?.Invoke("处理事件出现错误", "重要"); OnSubMessage?.Invoke("事件数据反序列化失败", "重要"); OnException?.Invoke(exception); } } _isListening = false; }
public async Task RunServerAsync() { OnSubMessage?.Invoke("服务启动中......", "重要"); //第一步:创建ServerBootstrap实例 var bootstrap = new ServerBootstrap(); //第二步:绑定事件组 IEventLoopGroup mainGroup = new MultithreadEventLoopGroup(1); //主工作线程组 IEventLoopGroup workGroup = new MultithreadEventLoopGroup(); //工作线程组 bootstrap.Group(mainGroup, workGroup); //第三步:绑定服务端的通道 bootstrap.Channel <TcpServerSocketChannel>();// 设置通道模式为TcpSocket //第四步:配置处理器 bootstrap.Option(ChannelOption.SoBacklog, 8192); bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //pipeline.AddLast(new HttpServerCodec()); //pipeline.AddLast(new HttpObjectAggregator(65536)); pipeline.AddLast(new TcpServerHandler()); })); //第五步:配置主机和端口号 string hostName = Dns.GetHostName(); IPAddress[] ipAddresses = Dns.GetHostAddresses(hostName); ipAddresses = ipAddresses.Where(m => m.ToString().IsIPv4()).ToArray(); var host = ConfigHelper.Configuration["ServerConfig:Host"]; bool trueAddress = ipAddresses.Any(m => host.Equals(m.ToString())); IPAddress iPAddress = trueAddress ? IPAddress.Parse(host) : ipAddresses[0]; var port = ConfigHelper.Configuration["ServerConfig:Port"]; IChannel bootstrapChannel = await bootstrap.BindAsync(iPAddress, int.Parse(port)); OnSubMessage?.Invoke("服务启动成功", "重要"); OnMessage?.Invoke($"已监听http://{iPAddress}:{int.Parse(port)}"); //第六步:停止服务 OnMessage?.Invoke("输入Stop停止服务"); string inputKey = string.Empty; while (!string.Equals(inputKey, "Stop", StringComparison.Ordinal)) { inputKey = OnGetCommand?.Invoke(); if (!string.Equals(inputKey, "Stop", StringComparison.Ordinal)) { OnException?.Invoke(new Exception("未识别命令请重新输入")); } } OnSubMessage?.Invoke("正在停止服务......", "重要"); await bootstrapChannel.CloseAsync(); OnSubMessage?.Invoke("服务已停止", "重要"); }
public virtual async Task RunAsync(ServerConfig serverConfig) { ServerConfig = serverConfig; OnSubMessage?.Invoke("服务启动中......", "重要"); //第一步:创建ServerBootstrap实例 var bootstrap = new ServerBootstrap(); //第二步:绑定事件组 IEventLoopGroup mainGroup = new MultithreadEventLoopGroup(1); IEventLoopGroup workGroup = new MultithreadEventLoopGroup(); bootstrap.Group(mainGroup, workGroup); //第三步:绑定服务端的通道 bootstrap.Channel <TcpServerSocketChannel>(); //第四步:配置处理器 bootstrap.Option(ChannelOption.SoBacklog, 8192); bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel => { try { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new HttpServerCodec()); pipeline.AddLast(new HttpObjectAggregator(655300000)); var channelHandler = Service.GetService <ServerChannelHandler>(); if (channelHandler == null) { return; } if (OnException != null) { channelHandler.OnException += OnException; } channelHandler.OnMessage += OnMessage; OnConfigHandler?.Invoke(channelHandler); pipeline.AddLast(channelHandler); } catch (Exception exception) { OnException?.Invoke(exception); } })); //第五步:配置主机和端口号 IPAddress ipAddress = GetTrueIPAddress(); _bootstrapChannel = await bootstrap.BindAsync(ipAddress, ServerConfig.Port); OnSubMessage?.Invoke("服务启动成功", "重要"); }
private async Task TestRun() { await Task.Run(() => { OnSubMessage?.Invoke("服务启动成功", "重要"); OnMessage?.Invoke("输入Stop停止服务"); string inputKey = string.Empty; while (!string.Equals(inputKey, "Stop", StringComparison.Ordinal)) { inputKey = OnGetCommand?.Invoke(); if (!string.Equals(inputKey, "Stop", StringComparison.Ordinal)) { OnException?.Invoke(new Exception("未识别命令请重新输入")); } } OnSubMessage?.Invoke("正在停止服务", "重要"); OnSubMessage?.Invoke("服务已停止", "重要"); }); }
/// <summary> /// 开始监听 /// </summary> /// <returns></returns> private async void StartListeningAsync() { try { if (_isListening) { return; } _isListening = true; while (ClientWebSocket.State == WebSocketState.Open) { var serverByteArray = new byte[655300000]; var buffer = new ArraySegment <byte>(serverByteArray); WebSocketReceiveResult wsData = await ClientWebSocket.ReceiveAsync(buffer, _cancellationToken); var bRec = new byte[wsData.Count]; Array.Copy(serverByteArray, bRec, wsData.Count); string eventJson = _clientConfig.EncodingType.GetString(bRec); OnEventMessage?.Invoke(eventJson); IEvent @event = eventJson.JsonToObject <BaseEvent>(); IEventHandler eventHandler = _eventBus.GetEventHandler(@event.EventHandler); @event = (IEvent)eventJson.JsonToObject(eventHandler.EventType); await eventHandler.HandlerAsync(@event, ClientWebSocket); } } catch (Exception exception) { if (_isManualClose) { return; } await StopAsync(false); OnSubMessage?.Invoke("与服务器断开连接", "重要"); OnException?.Invoke(exception); OnClose?.Invoke(); } finally { _isListening = false; } }
public async Task RunServerAsync() { OnSubMessage?.Invoke("服务启动中......", "重要"); //第一步:创建ServerBootstrap实例 var bootstrap = new ServerBootstrap(); //第二步:绑定事件组 IEventLoopGroup mainGroup = new MultithreadEventLoopGroup(1); //主工作线程组 IEventLoopGroup workGroup = new MultithreadEventLoopGroup(); //工作线程组 bootstrap.Group(mainGroup, workGroup); //第三步:绑定服务端的通道 bootstrap.Channel <TcpServerSocketChannel>();// 设置通道模式为TcpSocket //第四步:配置处理器 bootstrap.Option(ChannelOption.SoBacklog, 8192); bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new HttpServerCodec()); pipeline.AddLast(new HttpObjectAggregator(65536)); var handler = DIHelper.GetService <HttpChannelHandler>(); if (OnException != null) { handler.OnException += OnException; } pipeline.AddLast(handler);//注入HttpChannelHandler })); //第五步:配置主机和端口号 var iPAddress = GetTrueIPAddress(); //获得真实IP地址 var port = ConfigHelper.Configuration["ServerConfig:Port"]; IChannel bootstrapChannel = await bootstrap.BindAsync(iPAddress, int.Parse(port)); OnSubMessage?.Invoke("服务启动成功", "重要"); OnMessage?.Invoke($"已监听http://{iPAddress}:{int.Parse(port)}"); //第六步:停止服务 WaitServerStop();//等待服务停止 OnSubMessage?.Invoke("正在停止服务......", "重要"); await bootstrapChannel.CloseAsync(); OnSubMessage?.Invoke("服务已停止", "重要"); }
public async Task RunAsync() { OnSubMessage?.Invoke("连接服务中......", "重要"); //第一步:创建ServerBootstrap实例 var bootstrap = new Bootstrap(); //第二步:绑定事件组 workGroup = new MultithreadEventLoopGroup(); bootstrap.Group(workGroup); //第三部:绑定通道 bootstrap.Channel <TcpSocketChannel>(); //第四步:配置处理器 bootstrap.Option(ChannelOption.TcpNodelay, true); var builder = new UriBuilder { Scheme = _clientConfig.IsWss ? "wss" : "ws", Host = _clientConfig.Host, Port = _clientConfig.Port, Path = _clientConfig.Path }; WebSocketClientHandshaker clientHandshaker = WebSocketClientHandshakerFactory.NewHandshaker(builder.Uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()); var handler = new ClientChannelHandler(clientHandshaker); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(null))); pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.Instance, handler); })); Channel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(_clientConfig.Host), _clientConfig.Port)); await handler.HandshakeCompletion; }
public async Task ReconnectionAsync() { if (_clientConfig.ReconnectionNumber > 0 && _reconnectionNumber >= _clientConfig.ReconnectionNumber) { var exception = new MateralDotNettyException($"已连接失败{_reconnectionNumber}次,请联系管理员。"); OnException?.Invoke(exception); await StopAsync(); throw exception; } if (_clientConfig.ReconnectionInterval < 1000) { throw new MateralDotNettyException("至少等待1000ms"); } if (_isManualClose) { return; } OnSubMessage?.Invoke($"[{_reconnectionNumber + 1}]WebSocketClient将在{_clientConfig.ReconnectionInterval / 1000f:N2}秒后重新连接....", "重要"); await Task.Delay(_clientConfig.ReconnectionInterval, _cancellationToken); _reconnectionNumber++; await StartAsync(); }