private void SendP2pInternal( NetDataWriter writer, ushort sessionId, DeliveryMethod deliveryMethod) { if (deliveryMethod == DeliveryMethod.Tcp) { _logger.LogError("not support tcp transfer in p2p"); return; } if (sessionId == SessionId) { // 내가 받아야 한다면 _readerForSendInternal.SetSource(writer); OnP2pReceive(this, _readerForSendInternal); } else { var member = P2pGroup.Find(sessionId); if (member != null) { member.SendAsync(writer, deliveryMethod); } } }
/// <summary> /// 나 자산이 마스터인지 여부 /// </summary> /// <returns>마스터 여부</returns> public bool MasterIsMine() { if (P2pGroup == null) { return(false); } return(P2pGroup.MasterIsMine()); }
public void Run() { var serverOption = new ServerOption() { Name = "SampleGameServer", TcpServerPort = 12000, IsServiceUdp = true, UdpServerPort = 12001, MaxSession = 100, }; var loggerFactory = DefaultLoggerFactory.Create( builder => { builder.SetMinimumLevel(LogLevel.Information); builder.AddConsoleLogger(); } ); var statistics = new NetStatistic(); var sessionFactory = new DefaultSessionFactory( serverOption, loggerFactory, statistics, (createInfo) => { return(new UserSession(createInfo)); }); _server = new NetServer( serverOption, statistics, loggerFactory, sessionFactory); _server.AddRpcService(new LoginRpcServiceSession()); _server.StartAsync().Wait(); _p2pGroup = _server.P2pManager.CreateP2pGroup(); while (true) { var key = Console.ReadKey(); if (key.Key == ConsoleKey.Escape) { Console.WriteLine("quit"); break; } } _server.StopAsync().Wait(); }
private void SendP2pInternal( NetDataWriter writer, DeliveryTarget deliveryTarget, DeliveryMethod deliveryMethod) { if (deliveryMethod == DeliveryMethod.Tcp) { _logger.LogError("not support tcp transfer in p2p"); return; } if (P2pGroup == null) { _logger.LogWarning("No joined any P2pGroup"); return; } if (deliveryTarget == DeliveryTarget.All) { P2pGroup.SendAll(writer, deliveryMethod); _readerForSendInternal.SetSource(writer); OnP2pReceive(this, _readerForSendInternal); } else if (deliveryTarget == DeliveryTarget.Others) { P2pGroup.SendAll(writer, deliveryMethod); } else if (deliveryTarget == DeliveryTarget.Master) { var member = P2pGroup.Find(P2pGroup.MasterSessionId); if (member != null) { if (member.IsMine()) { // 내가 마스터라면 바로 호출함 _readerForSendInternal.SetSource(writer); OnP2pReceive(this, _readerForSendInternal); } else { member.SendAsync(writer, deliveryMethod); } } } }
public async Task Start() { // 서버 옵션을 정의 var serverOption = new ServerOption() { Name = "StarterServer", TcpServerPort = 12000, IsServiceUdp = true, UdpServerPort = 12001, MaxSession = 1000, IsCheckAlive = true, CheckAliveInterval = 50000, CheckAliveTimeout = 60000, }; // 로거 팩토리를 생성 var loggerFactory = DefaultLoggerFactory.Create( builder => { builder.SetMinimumLevel(LogLevel.Information); builder.AddConsoleLogger(); } ); var statistics = new NetStatistic(); // UserSession 을 사용하기 위해서 팩토리를 만듬 var sessionFactory = new DefaultSessionFactory( serverOption, loggerFactory, statistics, (createInfo) => { return(new UserSession(createInfo)); }); // 서버를 생성 _server = new NetServer( serverOption, statistics, loggerFactory, sessionFactory); // 자동으로 생성된 Rpc 서비스를 등록함 _server.AddRpcService(new LoginRpcServiceSession()); _server.AddRpcService(new ShopRpcServiceSession()); // P2p 그룹을 만듬 (현재는 1개만 필요하니 한개만 만듬. 여러개 생성가능) _p2pGroup = _server.P2pManager.CreateP2pGroup(); // 서버를 시작함 await _server.StartAsync(); // 메인스레드에 키 입력을 받을 수 있게 함 while (true) { var key = Console.ReadKey(); if (key.Key == ConsoleKey.Escape) { Console.WriteLine("quit"); break; } } // 서버 정지 await _server.StopAsync(); }
/// <summary> /// P2P 그룹의 모든 유저에게 데이터를 전송함 /// </summary> /// <param name="dataWriter">전송할 데이터</param> /// <param name="deliveryMethod">전송 방식</param> public void SendAll(NetDataWriter dataWriter, DeliveryMethod deliveryMethod) { P2pGroup?.SendAll(dataWriter, deliveryMethod); }
public async Task Test( [Values(3)] int clientCount, [Values(1)] int sendCount) { var serverTcs = new TaskCompletionSource <string>(); int receivedUnreliableCount = 0; int receivedTcpCount = 0; NetServer server = new NetServer( new ServerOption() { Name = "TestServer", TcpServerPort = 9000, IsServiceUdp = true, UdpServerPort = 9001, TcpBackLog = Math.Max(clientCount, 512), MaxSession = clientCount, }); server.OnSessionReceived += (ISession session, NetDataReader reader) => { var text = reader.ReadString(); var writer = NetPool.DataWriterPool.Alloc(); try { if (text == "Join") { var result = _p2pGroup.Join(session as ServerSession); Console.WriteLine($"P2p joined {result}"); } else if (text == "Leave") { var result = _p2pGroup.Leave(session as ServerSession); Console.WriteLine($"P2p leaved {result}"); } else if (text == "Unreliable") { Interlocked.Increment(ref receivedUnreliableCount); writer.Write("Unreliable"); session.SendAsync(writer, DeliveryMethod.Unreliable); } else { Interlocked.Increment(ref receivedTcpCount); if (text == "Finish") { writer.Write("Finish"); } else { writer.Write($"Hello Client{session.SessionId}"); } session.SendAsync(writer, DeliveryMethod.Tcp); } } finally { NetPool.DataWriterPool.Free(writer); } return(Task.CompletedTask); }; server.OnSessionErrored += (ISession session, Exception ex) => { serverTcs.TrySetException(ex); Assert.Fail(ex.ToString()); }; await server.StartAsync(); Assert.AreEqual("Started", server.State.ToString()); _p2pGroup = server.P2pManager.CreateP2pGroup(); List <Task <NetClient> > taskList = new List <Task <NetClient> >(); for (int i = 0; i < clientCount; i++) { taskList.Add(WorkClient(i, sendCount)); } await Task.WhenAny(Task.WhenAll(taskList), serverTcs.Task); Assert.AreEqual(clientCount, server.SessionCount); foreach (var task in taskList) { task.Result.Close(); } await Task.Delay(1000); Assert.AreEqual(0, server.SessionCount); Assert.AreEqual(0, _p2pGroup.MemberCount); await server.StopAsync(); await Task.Delay(1000); Assert.AreEqual("Stopped", server.State.ToString()); Console.WriteLine($"Server receivedTcpCount : {receivedTcpCount}"); Console.WriteLine($"Server receivedUnreliableCount : {receivedUnreliableCount}"); Console.WriteLine("****** PacketPool ******"); Console.WriteLine(NetPool.PacketPool.ToString()); Console.WriteLine(""); Console.WriteLine("****** DataWriterPool ******"); Console.WriteLine(NetPool.DataWriterPool.ToString()); Console.WriteLine(""); Assert.AreEqual(clientCount * sendCount, receivedTcpCount); Assert.AreEqual(0, NetPool.PacketPool.AllocCount); Assert.AreEqual(0, NetPool.DataWriterPool.AllocCount); Assert.Pass(); }