static async Task Init() { LoggerManager.InitLogger(new LogConfig()); SimpleSocketConfig simpleSocketConfig = new SimpleSocketConfig() { Port = 6868 }; long i = 0; var host = SuperSocketHostBuilder <TestSessionData> .Create <BinaryRequestInfo, DefaultFixedHeaderPipelineFilter>(simpleSocketConfig) .UseHostedService <CSuperSocketService <TestSessionData, BinaryRequestInfo> >() .UsePackageHandler(async(session, requestInfo) => { i++; if (session.DataContext == null) { session.DataContext = new TestSessionData() { Name = i.ToString() }; } // await Task.Factory.StartNew(()=> { var colorf = i % 2 == 0 ? ConsoleColor.Red : ConsoleColor.Green; IOHelper.WriteLine(requestInfo.OriBuffer.ToHex(), colorf); if (i % 100 == 0) { Console.Clear(); } await session.SendAsync(requestInfo.Body.ToArray()); // }); }) .Build(); await host.RunAsync(); }
protected override Task ExecuteAsync(CancellationToken stoppingToken) { var hosting = SuperSocketHostBuilder.Create <TextPackageInfo>() .UseClearIdleSession() .ConfigureSuperSocket(opts => { opts.AddListener(new ListenOptions() { Ip = "Any", Port = 10808 }); }) .UseSession <JTT808TcpSession>() .UseSessionHandler(onConnected: async(s) => { await Task.CompletedTask; }, onClosed: async(s, v) => { await Task.CompletedTask; }) .UsePackageHandler(async(s, p) => { await Task.CompletedTask; }) .UseInProcSessionContainer() .UseMiddleware <InProcSessionContainerMiddleware>() .BuildAsServer(); hosting.StartAsync(); return(Task.CompletedTask); }
static IHostBuilder CreateSocketServerBuilder() { return(SuperSocketHostBuilder.Create <StringPackageInfo, CommandLinePipelineFilter>() .UseCommand((commandOptions) => { // register commands one by one commandOptions.AddCommand <ADD>(); commandOptions.AddCommand <MULT>(); commandOptions.AddCommand <SUB>(); // register all commands in one aassembly //commandOptions.AddCommandAssembly(typeof(SUB).GetTypeInfo().Assembly); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary <string, string> { { "serverOptions:name", "TestServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "4040" } }); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); })); }
static async Task Main(string[] args) { var host = SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>() .UsePackageHandler(async(s, p) => { await s.SendAsync(Encoding.UTF8.GetBytes(p.Text + "\r\n")); }) .ConfigureSuperSocket(options => { options.Name = "Echo Server"; options.Listeners = new [] { new ListenOptions { Ip = "Any", Port = 4040 } }; }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .Build(); await host.RunAsync(); }
protected async Task RunTaskOne(CancellationToken stoppingToken) { Task.Run(() => { LogHelper.Error("FetchDataService start01"); //如果服务被停止,那么下面的IsCancellationRequested会返回true,我们就应该结束循环 //while (!stoppingToken.IsCancellationRequested) { LogHelper.Error("FetchDataService start02"); //LogHelper.Error("Consume Scoped Service Hosted Service is working"); var host = SuperSocketHostBuilder.Create <StringPackageInfo, CommandLinePipelineFilter>() .UsePackageHandler(async(s, p) => { // handle packages LogHelper.Error("handle packages"); LogHelper.Error("MESSAGE" + JsonConvert.SerializeObject(p.Key)); using (var scope = _serviceScopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService <IParseData>(); //other logic LogHelper.Error("FetchDataService ProcessDATA"); context.ProcessDATA(p.Key); } }).UseSession <MyAppSession>() .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .Build(); host.RunAsync(); } }, stoppingToken); }
public async Task RunAsync() { var host = SuperSocketHostBuilder.Create <StringPackageInfo, CommandLinePipelineFilter>() .UseCommand(options => { options.AddCommand <ADD>(); options.AddCommand <MULT>(); // ? 感觉全局的不生效 //options.AddGlobalCommandFilter<AsyncCommandFilterAttribute>(); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureSuperSocket(options => { options.Name = "Command Server"; options.Listeners = new[] { new ListenOptions { Ip = "Any", Port = 4040 } }; }).Build(); await host.RunAsync(); }
static void Main(string[] args) { var t = Task.Factory.StartNew(async() => { var host = SuperSocketHostBuilder.Create <StringPackageInfo, CommandLinePipelineFilter>() .UsePackageHandler(async(s, p) => { await s.SendAsync(Encoding.UTF8.GetBytes(p.Key.ToString() + "\r\n")); }) .UseSession <PlaySession>() .UseHostedService <GameService <StringPackageInfo> >() .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary <string, string> { { "serverOptions:name", "TestServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "5040" } }); }) .Build(); await host.RunAsync(); }); Console.ReadLine(); }
static IHostBuilder CreateSocketServerBuilder() { return(SuperSocketHostBuilder.Create <PackageInfo, RemoteCommon.CommandLinePipelineFilter>() .UseCommand((commandOptions) => { commandOptions.AddCommand <ConnectCommand>(); commandOptions.AddCommand <OutputCommand>(); commandOptions.AddCommand <ExecuteCommand>(); commandOptions.AddCommand <ListAgentCommand>(); commandOptions.AddCommand <ListClientCommand>(); commandOptions.AddCommand <DisconnectCommand>(); commandOptions.AddCommand <PingCommand>(); //commandOptions.AddCommandAssembly(typeof(Program).GetTypeInfo().Assembly); }) .ConfigureServices( (hostCtx, services) => { services.AddSingleton <IPackageDecoder <PackageInfo>, PackageDecoder>(); } ) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); })); }
static async Task Main(string[] args) { var host = SuperSocketHostBuilder.Create <MyPackage, MyPackageFilter>() .ConfigurePackageHandler(async(s, p) => { // handle package await Task.Delay(0); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureSuperSocket(options => { options.Name = "CustomProtocol Server"; options.Listeners = new [] { new ListenOptions { Ip = "Any", Port = 4040 } }; }).Build(); await host.RunAsync(); }
static void Main(string[] args) { Task.Factory.StartNew(async() => { var host = SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>() .UsePackageHandler(async(s, p) => { await s.SendAsync(Encoding.UTF8.GetBytes(p.Text.ToString() + "\r\n")); }) // .UseCommand((commandOptions)=>{ // commandOptions.AddCommand<ADD>(); // }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary <string, string> { { "serverOptions:name", "TestServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "4040" } }); }).Build(); await host.RunAsync(); }); Console.ReadLine(); Console.WriteLine("Hello World!"); }
protected SuperSocketHostBuilder <TPackageInfo> CreateSocketServerBuilder <TPackageInfo>(Func <object, IPipelineFilter <TPackageInfo> > filterFactory, IHostConfigurator configurator = null) where TPackageInfo : class { var hostBuilder = SuperSocketHostBuilder.Create <TPackageInfo>(); hostBuilder.UsePipelineFilterFactory(filterFactory); return(Configure(hostBuilder, configurator) as SuperSocketHostBuilder <TPackageInfo>); }
protected SuperSocketHostBuilder <TPackageInfo> CreateSocketServerBuilder <TPackageInfo, TPipelineFilter>(IHostConfigurator configurator = null) where TPackageInfo : class where TPipelineFilter : IPipelineFilter <TPackageInfo>, new() { var hostBuilder = SuperSocketHostBuilder.Create <TPackageInfo>(); hostBuilder.UsePipelineFilter <TPipelineFilter>(); return(Configure(hostBuilder, configurator) as SuperSocketHostBuilder <TPackageInfo>); }
public static WebSocketHostBuilder Create(SuperSocketHostBuilder <WebSocketPackage> hostBuilder) { return(hostBuilder.UsePipelineFilter <WebSocketPipelineFilter>() .UseWebSocketMiddleware() .ConfigureServices((ctx, services) => { services.AddSingleton <IPackageHandler <WebSocketPackage>, WebSocketPackageHandler>(); }) as WebSocketHostBuilder); }
private void CreateHost(ushort port, X509Certificate certificate) { _host = SuperSocketHostBuilder.Create <Request, FixedHeaderRequestDecoder>() .UsePackageHandler(async(session, request) => { try { var result = await ProcessRequest(request, session); switch (result) { case Response response: await session.SendAsync(_responseEncoder, response); break; case Responses responses: { await foreach (var response1 in responses) { await session.SendAsync(_responseEncoder, response1); } break; } } } catch (Exception e) { Logger.Warn(e); } }) .ConfigureSuperSocket((option) => { option.Name = "Otokoneko Manga Server"; option.Listeners = new List <ListenOptions>() { new ListenOptions() { Security = SslProtocols.Tls12, Ip = "Any", Port = port, BackLog = 100, CertificateOptions = new CertificateOptions() { Certificate = certificate } } }; option.MaxPackageLength = 64 * 1024 * 1024; }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.ClearProviders(); }) .Build(); }
static async Task Main(string[] args) { var host = SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>() .ConfigurePackageHandler(async(s, p) => { await s.SendAsync(Encoding.UTF8.GetBytes(p.Text + "\r\n")); }) .ConfigureLogging((hostCtx, loggingBuilder) => { // register your logging library here loggingBuilder.AddConsole(); }).Build(); await host.RunAsync(); }
public async Task RunAsync() { var host = SuperSocketHostBuilder.Create <StringPackageInfo, CommandLinePipelineFilter>() .ConfigurePackageHandler(async(s, package) => { var result = 0; switch (package.Key.ToUpper()) { case ("ADD"): result = package.Parameters .Select(p => int.Parse(p)) .Sum(); break; case ("SUB"): result = package.Parameters .Select(p => int.Parse(p)) .Aggregate((x, y) => x - y); break; case ("MULT"): result = package.Parameters .Select(p => int.Parse(p)) .Aggregate((x, y) => x * y); break; } await s.SendAsync(Encoding.UTF8.GetBytes(result.ToString() + "\r\n")); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureSuperSocket(options => { options.Name = "Echo Server"; options.Listeners = new [] { new ListenOptions { Ip = "Any", Port = 4040 } }; }).Build(); await host.RunAsync(); }
static IHostBuilder CreateSocketServerBuilder() { return(SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>() .ConfigurePackageHandler(async(s, p) => { await s.Channel.SendAsync(Encoding.UTF8.GetBytes(p.Text + "\r\n")); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary <string, string> { { "serverOptions:name", "TestServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "4040" } }); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); })); }
static async System.Threading.Tasks.Task Main(string[] args) { var host = SuperSocketHostBuilder.Create <JT808Package, MyPipelineFilter>(args) .ConfigureSuperSocket(options => { options.AddListener(new ListenOptions { Ip = "Any", Port = 4040 }) .AddListener(new ListenOptions() { Ip = "Any", Port = 8888 }); }) .UseSession <MySession>() .UseSessionHandler(s => { s["Identify"] = "0x001"; return(default);
public async Task RunAsync() { var host = SuperSocketHostBuilder.Create <StringPackageInfo, CommandLinePipelineFilter>() // .UsePackageHandler(async (s, p) => // { // await s.SendAsync(Encoding.UTF8.GetBytes(p.Key.ToString() + "\r\n")); // }) .UseCommand((commandOptions) => { //commandOptions.AddCommand<GOROOM>(); // register all commands in one aassembly commandOptions.AddCommandAssembly(typeof(PWD).GetTypeInfo().Assembly); }) .UseSession <ChatorSession>() .UseInProcSessionContainer() .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureServices((hostCtx, services) => { services.AddSingleton <IRoomManager>(new RoomManager(roomNumber: 3)); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary <string, string> { { "serverOptions:name", "TestServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "4040" } }); }).Build(); //var sc = host.GetSessionContainer(); // sc.GetSessions().ToList().ForEach(async e => await e.Channel.SendAsync(Encoding.UTF8.GetBytes("s"))); //GlobalCache.AppServer = host; await host.RunAsync(); }
public async Task TestStartWithDefaultConfig() { var server = default(IServer); using (var host = SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>() .UseSessionHandler(s => { server = s.Server as IServer; return(new ValueTask()); }) .Build()) { await host.StartAsync(); var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await client.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4040)); OutputHelper.WriteLine("Connected."); await Task.Delay(1000); Assert.Equal("TestServer", server.Name); Assert.Equal(1, server.SessionCount); OutputHelper.WriteLine("SessionCount:" + server.SessionCount); client.Shutdown(SocketShutdown.Both); client.Close(); await Task.Delay(1000); Assert.Equal(0, server.SessionCount); OutputHelper.WriteLine("SessionCount:" + server.SessionCount); await host.StopAsync(); } }
public ISuperSocketHostBuilder GetServerHostBuilder() { if (Builder != null) { return(Builder); } var jttTypes = new Dictionary <Type, Type>(); var supersocketHostBuilder = SuperSocketHostBuilder.Create <TPackageInfo>(); IHostBuilder hostBuilder = null; if (Options.ServerOptions != null) { supersocketHostBuilder.UsePackageHandler( Options.ServerOptions.PackageHandler, Options.ServerOptions.ErrorHandler); supersocketHostBuilder.UseSessionHandler( Options.ServerOptions.OnConnected, Options.ServerOptions.OnClosed); if (Options.ServerOptions.InProcSessionContainer) { supersocketHostBuilder.UseInProcSessionContainer(); } hostBuilder = supersocketHostBuilder.ConfigureServices((context, services) => { Options.ServerOptions.ConfigureServices?.Invoke(context, services); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary <string, string> { { "serverOptions:name", Options.ServerOptions?.Name ?? $"SuperSocket {(Options.ServerOptions.UseUdp?"UDP":"TCP")} Server" }, { "serverOptions:listeners:0:ip", Options.ServerOptions?.IP }, { "serverOptions:listeners:0:port", Options.ServerOptions?.Port.ToString() }, { "serverOptions:listeners:0:backLog", Options.ServerOptions?.BackLog.ToString() } }); Options.ServerOptions.ConfigureAppConfiguration?.Invoke(hostCtx, configApp); }); } if (Options.LoggingOptions != null) { hostBuilder = (hostBuilder ?? supersocketHostBuilder).ConfigureLogging((hostCtx, loggingBuilder) => { if (Options.LoggingOptions?.Provider != null) { loggingBuilder.AddProvider(Options.LoggingOptions.Provider); } if (Options.LoggingOptions?.AddConsole == true) { loggingBuilder.AddConsole(); } if (Options.LoggingOptions?.AddDebug != null) { loggingBuilder.AddDebug(); } }); } Builder = (hostBuilder ?? supersocketHostBuilder) as ISuperSocketHostBuilder; if (Options.ServerOptions.UseUdp) { Builder.UseUdp(); } return(Builder); }
protected IHostBuilder <TPackageInfo> CreateSocketServerBuilder <TPackageInfo, TPipelineFilter>(IHostConfigurator configurator = null) where TPackageInfo : class where TPipelineFilter : IPipelineFilter <TPackageInfo>, new() { return(Configure(SuperSocketHostBuilder.Create <TPackageInfo, TPipelineFilter>(), configurator) as IHostBuilder <TPackageInfo>); }
protected IHostBuilder <TPackageInfo> CreateSocketServerBuilder <TPackageInfo>(Func <object, IPipelineFilter <TPackageInfo> > filterFactory, IHostConfigurator configurator = null) where TPackageInfo : class { return(Configure(SuperSocketHostBuilder.Create <TPackageInfo>(filterFactory), configurator) as IHostBuilder <TPackageInfo>); }
static async Task Main(string[] args) { var host = SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>(args) .ConfigureSuperSocket(options => { options.AddListener(new ListenOptions { Ip = "Any", Port = 4040 }) .AddListener(new ListenOptions() { Ip = "Any", Port = 8888 }); }) .UseSession <MySession>() .UseSessionHandler(async s => { var data = new TcpPackage() { OpCode = OpCode.Connect, LocalName = "Server", RemoteName = "All", MessageType = MessageType.Text, Message = String.Empty, Clients = _clients }; var sessions = _sessionContainer.GetSessions(); foreach (var session in sessions) { string da = data.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(da))); } }, async(s, e) => { _clients = _clients.Where(x => x.SessionId != s.SessionID).ToList(); var sessions = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); var data = new TcpPackage() { OpCode = OpCode.Connect, LocalName = "Server", RemoteName = "All", MessageType = MessageType.Text, Message = "Connect Success.", Clients = _clients.Count() == 1 ? null : _clients }; foreach (var session in sessions) { string val = data.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(val))); } }) .UsePackageHandler(async(s, p) => { var package = TcpPackage.JsonToPackage(p.Text); //Console.WriteLine($"\n{p.Text}\n"); switch (package.OpCode) { case OpCode.Connect: _clients.Add(new ClientInfo() { Username = package.LocalName, SessionId = s.SessionID }); var sessions = _sessionContainer.GetSessions(); foreach (var session in sessions) { var connectData = new TcpPackage() { OpCode = OpCode.Connect, MessageType = MessageType.Text, LocalName = "Server", RemoteName = _clients.Where(x => s.SessionID == x.SessionId)?.FirstOrDefault() != null ? _clients.FirstOrDefault(x => s.SessionID == x.SessionId)?.Username : null, Message = "Connect Success.", Clients = _clients.Where(x => x.SessionId != session.SessionID).ToList() }; string conn = connectData.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(conn))); } break; case OpCode.All: TcpPackage allData = null; switch (package.MessageType) { case MessageType.Text: allData = new TcpPackage() { OpCode = OpCode.All, MessageType = MessageType.Text, LocalName = package.LocalName, RemoteName = "All", Message = package.Message }; break; case MessageType.Image: //var imgConfig = new UdpConfigPackage() //{ // SendEndPoint = $"{((IPEndPoint)s.LocalEndPoint).Address}|{11000}", // ReceiveEndPoint = $"{((IPEndPoint)s.RemoteEndPoint).Address}|{12000}" //}; allData = new TcpPackage() { OpCode = OpCode.All, MessageType = MessageType.Image, LocalName = "Server", RemoteName = package.LocalName, Config = null }; break; case MessageType.File: allData = new TcpPackage() { OpCode = OpCode.All, MessageType = MessageType.File, LocalName = "Server", RemoteName = package.LocalName, Message = s.LocalEndPoint.ToString() }; break; } var aSessionClients = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); foreach (var sClient in aSessionClients) { string val = allData.ToString(); await sClient.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(val))); } break; case OpCode.Single: TcpPackage singleData = null; switch (package.MessageType) { case MessageType.Text: singleData = new TcpPackage() { OpCode = OpCode.Single, MessageType = MessageType.Text, LocalName = package.LocalName, RemoteName = package.RemoteName, Message = package.Message }; break; case MessageType.Image: //var imgConfig = new UdpConfigPackage() //{ // SendEndPoint = $"{((IPEndPoint)s.LocalEndPoint).Address}.{11000}", // ReceiveEndPoint = $"{((IPEndPoint)s.RemoteEndPoint).Address}.{12000}" //}; singleData = new TcpPackage() { OpCode = OpCode.Single, MessageType = MessageType.Image, LocalName = "Server", RemoteName = package.LocalName, Message = null }; break; case MessageType.File: singleData = new TcpPackage() { OpCode = OpCode.Single, MessageType = MessageType.File, LocalName = package.LocalName, RemoteName = package.RemoteName, Message = s.LocalEndPoint.ToString() }; break; } var remoteSession = _clients.Where(y => y.Username == package.RemoteName); foreach (var rSession in remoteSession) { var sSessionClients = _sessionContainer.GetSessions() .Where(x => x.SessionID.Equals(rSession.SessionId)); foreach (var sClient in sSessionClients) { var sing = singleData.ToString(); await sClient.SendAsync( new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(sing))); } } break; case OpCode.DisConnect: break; case OpCode.Confirm: var imgConfig = new UdpConfigPackage() { SendEndPoint = $"{((IPEndPoint)s.LocalEndPoint).Address}|{11000}", ReceiveEndPoint = $"{((IPEndPoint)s.RemoteEndPoint).Address}|{12000}" }; TcpPackage confirmPackage = new TcpPackage() { OpCode = OpCode.Confirm, MessageType = package.MessageType, LocalName = package.LocalName, RemoteName = package.RemoteName, Message = "image", Config = imgConfig }; #region 测试数据 //var testleData = new TcpPackage() //{ // OpCode = OpCode.Confirm, // MessageType = MessageType.Text, // LocalName = package.LocalName, // RemoteName = package.RemoteName, // Message = JsonConvert.SerializeObject(imgConfig), // Config = imgConfig //}; //var testString = testleData.ToString(); #endregion var confirmMsg = confirmPackage.ToString(); await s.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(confirmMsg))); if (package.RemoteName.Equals("All")) { confirmPackage.OpCode = OpCode.All; } else { confirmPackage.OpCode = OpCode.Single; } var cRemoteSession = _sessionContainer.GetSessions() .Where(x => x.SessionID != s.SessionID); var confirm = confirmPackage.ToString(); foreach (var session in cRemoteSession) { await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(confirm))); } break; default: throw new ArgumentException(message: "op code error"); } }) .ConfigureErrorHandler((s, v) => { Console.WriteLine($"\n[{DateTime.Now}] [TCP] Error信息:" + s.SessionID.ToString() + Environment.NewLine); return(default);
static async Task Main(string[] args) { var host = SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>(args) .ConfigureSuperSocket(options => { options.AddListener(new ListenOptions { Ip = "Any", Port = 4041 }) .AddListener(new ListenOptions() { Ip = "Any", Port = 8888 }); }) .UseSession <MySession>() .UseSessionHandler(onConnected: async(s) => { Console.WriteLine($"\n[{DateTime.Now}] [TCP] 客户端上线:" + ++_tcpCount + Environment.NewLine); var data = new MessagePackage <TextMessageModel>() { OpCode = OpCode.Connect, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = "Server", RemoteName = "All" }, Clients = _clients }; var sessions = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); foreach (var session in sessions) { string da = data.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(da))); } }, onClosed: async(s, e) => { _clients = _clients.Where(x => x.SessionId != s.SessionID); var sessions = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); var data = new MessagePackage <TextMessageModel>() { OpCode = OpCode.Connect, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = "Server", TextMessage = "Connect Success." }, Clients = _clients.Count() == 1?null:_clients }; foreach (var session in sessions) { string val = data.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(val))); } Console.WriteLine($"\n[{DateTime.Now}] [TCP] 客户端下线:" + --_tcpCount + Environment.NewLine); }) .UsePackageHandler(async(s, p) => { Console.WriteLine($"\n[{DateTime.Now}] [TCP] 服务器信息:" + p.Text + Environment.NewLine); // Connect var package = JsonConvert.DeserializeObject <MessagePackage <TextMessageModel> >(p.Text); switch (package.OpCode) { case OpCode.Connect: _clients = _clients.Concat(new[] { new ClientInfo() { Username = package.Message.LocalName, SessionId = s.SessionID } }); var sessions = _sessionContainer.GetSessions(); foreach (var session in sessions) { var connectData = new MessagePackage <TextMessageModel>() { OpCode = OpCode.Connect, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = "Server", RemoteName = _clients.Where(x => s.SessionID == x.SessionId)?.FirstOrDefault().Username, TextMessage = "Connect Success." }, Clients = _clients.Where(x => x.SessionId != session.SessionID) }; string conn = connectData.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(conn))); } break; case OpCode.All: var allData = new MessagePackage <TextMessageModel>() { OpCode = OpCode.All, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = package.Message.LocalName, RemoteName = "All", TextMessage = package.Message.TextMessage } }; var asessionClients = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); foreach (var sClient in asessionClients) { string val = allData.ToString(); await sClient.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(val))); } break; case OpCode.Single: var singleData = new MessagePackage <TextMessageModel>() { OpCode = OpCode.Single, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = package.Message.LocalName, RemoteName = package.Message.RemoteName, TextMessage = package.Message.TextMessage } }; var remoteSession = _clients.Where(y => y.Username == package.Message.RemoteName); foreach (var rSession in remoteSession) { var ssessionClients = _sessionContainer.GetSessions() .Where(x => x.SessionID.Equals(rSession.SessionId)); foreach (var sClient in ssessionClients) { var sing = singleData.ToString(); await sClient.SendAsync( new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(sing))); } } break; case OpCode.Subscribe: default: throw new ArgumentException(message: "op code error"); } }) .ConfigureErrorHandler((s, v) => { Console.WriteLine($"\n[{DateTime.Now}] [TCP] Error信息:" + s.SessionID.ToString() + Environment.NewLine); return(default);
static async Task Main(string[] args) { var stack = new ConcurrentStack <IEasyClient <HttpResponse> >(); var lookupClient = new LookupClient(new LookupClientOptions { UseCache = true }); var notFoundNameValueCollection = new NameValueCollection { { "Content-Length", "0" } }; var notFoundHeader = new HttpHeader(notFoundNameValueCollection); var notFoundResp = new HttpResponse("HTTP/1.1", 404, "Not Found", notFoundHeader); notFoundResp.BuildData(); var responsePackageEncoder = new HttpResponsePackageEncoder(); var host = SuperSocketHostBuilder .Create <HttpRequest, GatewayService, HttpPipelineFilter>() .ConfigurePackageHandler <HttpRequest>(async(s, p) => { var appSession = (GatewaySession)s; var options = appSession.LifetimeScope.Resolve <IOptionsSnapshot <GatewayOptions> >(); var forwardConfig = options.Value.ForwardConfigs.FirstOrDefault(e => e.Match(p.Path)); if (forwardConfig == null) { await s.SendAsync(responsePackageEncoder, notFoundResp); return; } p.Header["host"] = forwardConfig.Target.Host; p.Path = forwardConfig.TransferPath(p.Path); var request = p.ToString(); if (!stack.TryPop(out var client)) { //client= new EasyClient<HttpResponse>(new BufferPipelineFilter()); client = new SecureClient <HttpResponse>(new BufferPipelineFilter()).AsClient(); } var result = await lookupClient.QueryAsync(forwardConfig.Target.Host, QueryType.A); var record = result.Answers.ARecords().FirstOrDefault(); await client.ConnectAsync(new IPEndPoint(record.Address, forwardConfig.Target.Port)); await client.SendAsync(new DefaultStringEncoder(), request); var response = await client.ReceiveAsync(); await client.CloseAsync(); stack.Push(client); if (response != null) { await s.SendAsync(responsePackageEncoder, response); } }, (s, e) => { return(new ValueTask <bool>()); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureServices((hostCtx, services) => { services.Configure <GatewayOptions>(hostCtx.Configuration.GetSection("Gateway")); }) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureContainer <ContainerBuilder>(builder => { builder.RegisterType <GatewaySessionFactory>().AsImplementedInterfaces().SingleInstance(); builder.RegisterType <GatewaySession>().InstancePerLifetimeScope(); }) .Build(); await host.RunAsync(); }
static void Main(string[] args) { var host = SuperSocketHostBuilder.Create <RPC, MyPackageFilter>(args) .UsePackageHandler(async(s, p) => { Console.WriteLine($"Code = {p.Code}"); var rpc = new RPC(); if (p.Code == TypeEnum.RPC_HELO) { var bytes1 = new List <Byte> { 0, 0, 0, 0, 0xa }; await s.SendAsync(bytes1.ToArray()); //var md = new RPC_HELO(p.Data.ToArray()); //check return; } else if (p.Code == TypeEnum.PULL_MD) { var md = new PULL_MD(p.Data.ToArray()); PULL_MD_RESULT result = new PULL_MD_RESULT(); //md 没问题就从数据库里面获取 获取之后返回 foreach (var item in md.funcInfos) { //从数据库里面取 var data = CacheHelper.Get(item); if (data != null && result.Result.FirstOrDefault(p => p.MetaData.func_name == data.MetaData.func_name) == null) { result.Found.Add(0); result.Result.Add(data); } else { result.Found.Add(1); //result.Result.Add(new func_info_t()); //result.Found.Add(0); } } rpc.Data = result.GetBytes().ToList(); rpc.Code = TypeEnum.PULL_MD_RESULT; await s.SendAsync(rpc.GetBytes()); } else if (p.Code == TypeEnum.PUSH_MD) { var md = new PUSH_MD(p.Data.ToArray()); var result = new PUSH_MD_RESULT(); foreach (var item in md.funcInfos) { //存储 result.ResultsFlags.Add(CacheHelper.Add(item)?1:0); } rpc.Data = result.GetBytes().ToList(); rpc.Code = TypeEnum.PUSH_MD_RESULT; await s.SendAsync(rpc.GetBytes()); } }) .ConfigureSuperSocket(options => { options.Name = "Echo Server"; //byte[] data = File.ReadAllBytes("lumen.p12"); options.AddListener(new ListenOptions { Ip = "Any", Port = 4443, Security = SslProtocols.Tls12, CertificateOptions = new CertificateOptions() { FilePath = "client.pfx", //ClientCertificateRequired = false, //Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate(data, "1164185642"), //Password = "******", //RemoteCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((OnRemoteCertificateValidationCallback)) } } ); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .Build(); host.RunAsync(); Console.ReadLine(); }