/// <summary> /// 增加工厂 /// </summary> /// <param name="factory"></param> public void AddFactory(PacketFactory factory) { if (factory.GetPacketId() < 0 || this.m_lstPacketFactorys == null || this.m_lstPacketFactorys.Length <= factory.GetPacketId() || this.m_lstPacketFactorys[factory.GetPacketId()] != null) { return; } this.m_lstPacketFactorys[factory.GetPacketId()] = factory; }
public override int SendWaypoints(IList <GlobalsatWaypoint> waypoints, IJobMonitor jobMonitor) { int nrSentWaypoints = 0; if (this.Open()) { try { foreach (GlobalsatWaypoint g in waypoints) { GlobalsatPacket packet = PacketFactory.SendWaypoints(this.FitnessDevice.configInfo.MaxNrWaypoints, new List <GlobalsatWaypoint> { g }); GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); int resp = response.ResponseSendWaypoints(); nrSentWaypoints += resp; if (resp <= 0) { jobMonitor.ErrorText = string.Format("Could only send {0} out of {1} waypoints. (Capacity {2}).", nrSentWaypoints, waypoints.Count, this.FitnessDevice.configInfo.MaxNrWaypoints); break; } } } catch (Exception ex) { jobMonitor.ErrorText = Properties.Resources.Device_SendWaypoints_Error + ex; } finally { this.Close(); } } if (!this.DataRecieved) { //Normal case NoCommunicationError(jobMonitor); } return(nrSentWaypoints); }
private void ListenForData() { int errCount = 0; while (tcpReady) { try { int opcode = tcpStream.ReadByte(); Debug.Log("Got " + opcode); if (opcode == -1) { //TODO Disconnected break; } Packet p = PacketFactory.GetPacket(opcode); if (p != null) { //Otherwise run in this thread (may be unsafe) p.HandlePacket(this); } else { Debug.LogError("Unknown Opcode: " + opcode); } errCount = 0; } catch (Exception e) { Debug.LogException(e); errCount++; if (errCount >= 3) { break; } } } }
public void Setup() { PacketFactory.Initialize <NoS0575Packet>(); Broadcaster.Reset(); GroupAccess.Instance.Groups = new ConcurrentDictionary <long, Group>(); for (byte i = 0; i < (byte)(GroupType.Group + 1); i++) { var handler = new GroupPacketController(); var session = new ClientSession(null, new List <PacketController> { handler }, null) { SessionId = i }; Broadcaster.Instance.RegisterSession(session); var acc = new AccountDto { Name = $"AccountTest{i}", Password = EncryptionHelper.Sha512("test") }; var charaDto = new CharacterDto { CharacterId = i, Name = $"TestExistingCharacter{i}", Slot = 1, AccountId = acc.AccountId, MapId = 1, State = CharacterState.Active }; session.InitializeAccount(acc); _handlers.Add(handler); handler.RegisterSession(session); var chara = charaDto.Adapt <Character>(); chara.Session = session; _characters.Add(i, chara); chara.Group.JoinGroup(chara); session.SetCharacter(chara); session.Character.MapInstance = new MapInstance(new Map(), Guid.NewGuid(), true, MapInstanceType.BaseMapInstance, null); } }
public void PacketFactory_BuildPacket_ProviderPacket_Normal() { InputController.EnableMock(); InputController.AddMockInput(SampleID); InputController.AddMockInput("N"); InputController.AddMockInput(SampleName); InputController.AddMockInput(SampleAddress); InputController.AddMockInput(SampleCity); InputController.AddMockInput(SampleState); InputController.AddMockInput(SampleZip); InputController.AddMockInput(SampleEmail); InputController.AddMockInput(SamplePassword); TextUI textUI = new TextUI(true); PacketFactory packetFactory = new PacketFactory(); var result = packetFactory.BuildPacket(textUI, "ProviderPacket", "UPDATE_PROVIDER"); Assert.IsNotNull(result); InputController.DisableMock(); }
public override void Flush() { if (Closed) { throw new InvalidOperationException("Stream is closed"); } if (Buf.Length > VBANPacket <T> .MaxSize) { throw new InvalidOperationException($"Buffer is too large, must be smaller than {VBANPacket<T>.MaxSize}"); } VBANPacket <T> packet = PacketFactory.Create(); packet.Data = Buf.Bytes; byte[] x; _client.Send(x = packet.Bytes, x.Length, IpEndPoint); Buf = new UnfinishedByteArray(VBANPacket <T> .MaxSize, true); }
public void GeneratePacketWithSpecialSeparator() { var dlgTest = new BlinitPacket { SubPackets = new List <BlinitSubPacket> { new BlinitSubPacket { RelatedCharacterId = 1, CharacterName = "test" }, new BlinitSubPacket { RelatedCharacterId = 2, CharacterName = "test2" } } }; var packet = PacketFactory.Serialize(new[] { dlgTest }); Assert.AreEqual( "blinit 1|test 2|test2", packet); }
public void Generate() { var characterTest = new Character { Name = "characterTest", Account = new AccountDto { Authority = AuthorityType.Administrator }, Level = 1, Inventory = new InventoryService(new List <Item>(), new WorldConfiguration()) }; var packet = PacketFactory.Serialize(new[] { new DelayPacket { Type = 3, Delay = 3000, Packet = characterTest.GenerateUseItem(PocketType.Main, 1, 2, 0) } }); Assert.AreEqual($"delay 3000 3 #u_i^1^0^1^1^2^0", packet); }
public void PacketFactoryTest() { //this test only tests the factory, not the packets //intialize factory PacketFactory.Initialize <WalkPacket>(); //1234 simulates packet header iterative number string equipPacket = "1234 equip 5 0 0.4903.5.0.0 2.340.0.0.0 3.720.0.0.0 5.4912.6.0.0 9.227.0.0.0 10.803.0.0.0 11.347.0.0.0 13.4146.0.0.0 14.4138.0.0.0"; EquipPacket serializedPacket = PacketFactory.Serialize <EquipPacket>(equipPacket); string deserializedEquipPacket = PacketFactory.Deserialize(serializedPacket); Assert.AreEqual(equipPacket, $"1234 {deserializedEquipPacket}"); //1234 simulates packet header iterative number string inPacket = "1234 in 1 ImACharacter - 1 80 116 0 2 1 0 3 0 -1.12.1.8.-1.-1.-1.-1.-1 100 100 0 -1 0 0 0 0 0 0 0 0 -1 - 1 0 0 0 0 1 0 0 0 10 0"; InPacket serializedInPacket = PacketFactory.Serialize <InPacket>(inPacket); string deserializedInPacket = PacketFactory.Deserialize(serializedInPacket); Assert.AreEqual(inPacket, $"1234 {deserializedInPacket}"); }
//not working, deletes all... public virtual int DeleteTracks(DateTime oldest, IJobMonitor jobMonitor) { int res = -1; try { if (this.Open()) { IList <GlobalsatPacket.TrackFileHeader> headers = this.ReadTrackHeaders(jobMonitor); IList <GlobalsatPacket.TrackFileHeader> fetch = new List <GlobalsatPacket.TrackFileHeader>(); foreach (GlobalsatPacket.TrackFileHeader t in headers) { if (t.StartTime < oldest) { fetch.Add(t); } } if (fetch.Count > 0) { GlobalsatPacket getDeleteTracks = PacketFactory.GetDeleteTracks(fetch); GlobalsatPacket2 response = (GlobalsatPacket2)SendPacket(getDeleteTracks); } res = fetch.Count; } } catch (Exception e) { jobMonitor.ErrorText = Properties.Resources.Device_OpenDevice_Error + e; //throw new Exception(Properties.Resources.Device_OpenDevice_Error + e); } finally { this.Close(); } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); } return(res); }
public void Setup() { PacketFactory.Initialize <NoS0575Packet>(); var builder = new ConfigurationBuilder(); SqlConnectionConfiguration databaseConfiguration = new SqlConnectionConfiguration(); builder.SetBasePath(Directory.GetCurrentDirectory() + _configurationPath); builder.AddJsonFile("database.json", false); builder.Build().Bind(databaseConfiguration); databaseConfiguration.Database = "postgresunittest"; var sqlconnect = databaseConfiguration; DataAccessHelper.Instance.EnsureDeleted(sqlconnect); ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo(_configurationPath + "/log4net.config")); Shared.Logger.Logger.InitializeLogger(LogManager.GetLogger(typeof(CharacterScreenPacketHandlerTests))); DataAccessHelper.Instance.Initialize(sqlconnect); DAOFactory.RegisterMapping(typeof(Character).Assembly); MapDTO map = new MapDTO() { MapId = 1 }; DAOFactory.MapDAO.InsertOrUpdate(ref map); acc = new AccountDTO() { Name = "AccountTest", Password = EncryptionHelper.Sha512("test") }; DAOFactory.AccountDAO.InsertOrUpdate(ref acc); CharacterDTO chara = new CharacterDTO() { Name = "TestExistingCharacter", Slot = 1, AccountId = acc.AccountId, MapId = 1, State = CharacterState.Active }; DAOFactory.CharacterDAO.InsertOrUpdate(ref chara); session.InitializeAccount(acc); handler = new CharacterScreenPacketController(); handler.RegisterSession(session); }
public IActionResult PostPacket([FromBody] PostedPacket postedPacket) { if (!ModelState.IsValid) { return(BadRequest()); } var message = PacketFactory.Deserialize(postedPacket.Packet); switch (postedPacket.ReceiverType) { case ReceiverType.All: ServerManager.Instance.Broadcast(message); break; case ReceiverType.OnlySomeone: ClientSession receiverSession; if (postedPacket.ReceiverCharacter.Name != null) { receiverSession = ServerManager.Instance.Sessions.Values.FirstOrDefault(s => s.Character?.Name == postedPacket.ReceiverCharacter.Name); } else { receiverSession = ServerManager.Instance.Sessions.Values.FirstOrDefault(s => s.Character?.CharacterId == postedPacket.ReceiverCharacter.Id); } if (receiverSession == null) { return(Ok()); } receiverSession.SendPacket(message); break; } return(Ok()); }
public void Connect(IPEndPoint remoteEndPoint) { socket.Connect(remoteEndPoint); networkStream = new NetworkStream(socket); Receiver = new Thread(() => { try { while (true) { Utils.ReadFull(networkStream, buffer, PacketFactory.PacketSize); IPacket header = PacketFactory.ParseHeader(buffer); chain.DoHandle(header); } } catch (SocketException) { if (socket.Connected) { throw; } } catch (IOException e) { if (e.InnerException != null && e.InnerException.GetType() != typeof(SocketException) && !socket.Connected) { return; } } finally { Dispose(); } }); Receiver.Name = "IBLVM Client Receiver"; Receiver.Start(); Status = (int)ClientSocketStatus.Handshaking; Utils.SendPacket(SocketStream, PacketFactory.CreateClientHello()); }
private void PackageHandler(Packet package) { switch (package.Action) { case ActionType.Heartbeat: Session.Refresh(); break; case ActionType.Request: SetupRequest(package.GetValue <Request>()); break; case ActionType.Response: break; default: var errPack = PacketFactory.CreateError("Unknown ActionType:{0}", package.Action); Session.Send(errPack); Session.Close(); break; } }
public void PacketFactoryTest() { // this test only tests the factory, not the packets intialize factory PacketFactory.Initialize <WalkPacket>(); Logger.InitializeLogger(LogManager.GetLogger(typeof(CoreTest))); // Equip Packet string equipPacket = "equip 5 0 0.4903.5.0.0 2.340.0.0.0 3.720.0.0.0 5.4912.6.0.0 9.227.0.0.0 10.803.0.0.0 11.347.0.0.0 13.4146.0.0.0 14.4138.0.0.0"; EquipPacket deserializedEquipPacket = PacketFactory.Deserialize <EquipPacket>(equipPacket); string serializedEquipPacket = PacketFactory.Serialize(deserializedEquipPacket); Assert.AreEqual(equipPacket, serializedEquipPacket); // In Packet string inPacket = "in 1 ImACharacter - 1 80 116 0 2 1 0 3 0 -1.12.1.8.-1.-1.-1.-1.-1 100 100 0 -1 0 0 0 0 0 0 0 0 -1 - 1 0 0 0 0 1 0 0 0 10 0"; InPacket deserializedInPacket = PacketFactory.Deserialize <InPacket>(inPacket); string serializedInPacket = PacketFactory.Serialize(deserializedInPacket); Assert.AreEqual(inPacket, serializedInPacket); // Walk Packet string walkPacket = "walk 3 115 1 11"; WalkPacket deserializedWalkPacket = PacketFactory.Deserialize <WalkPacket>(walkPacket); string serializedWalkPacket = PacketFactory.Serialize(deserializedWalkPacket); Assert.AreEqual(walkPacket, serializedWalkPacket); WalkPacket invalidWalkPacket = PacketFactory.Deserialize <WalkPacket>("walk 3a0 115 1 11"); Assert.IsNull(invalidWalkPacket); // Dialog Packet string dialogPacket = "dlg #walk^3^115^1^11 #walk^3^115^1^11 Do you really wanna walk this way?"; DialogPacket <WalkPacket, WalkPacket> deserializedDialogPacket = PacketFactory.Deserialize <DialogPacket <WalkPacket, WalkPacket> >(dialogPacket); string serializedDialogPacket = PacketFactory.Serialize(deserializedDialogPacket); Assert.AreEqual(dialogPacket, serializedDialogPacket); }
static void Main(string[] args) { var testPacket = PacketFactory.CreatePacket <MessagePacket>(); testPacket.Message = "Something"; testPacket.Sender = "Someone"; var packetJson = testPacket.ToJson(); Console.WriteLine(packetJson); PacketFactory.JsonToPacket(packetJson, out IPacket testDeserialize); switch (testDeserialize.Type) { case PacketType.Message: HandleMessage(testDeserialize as MessagePacket); break; } Console.ReadLine(); }
public override void Flush() { if (Closed) { throw new InvalidOperationException("Stream is closed"); } if (Buf.Length > VBANPacket <T> .MaxSize) { throw new InvalidOperationException( $"Buffer is too large, must be smaller than {VBANPacket<T>.MaxSize}"); } var packet = PacketFactory.Create(); packet.AttachData(Buf); byte[] x = packet; _client.Send(x, x.Length, IpEndPoint); Buf = new ByteArray(); }
void Awake() { if (_instance == null) { DontDestroyOnLoad(gameObject); _instance = this; } else { Destroy(gameObject); return; } UnityBinder.Inject(this); listener = new TcpListener(new IPEndPoint(IPAddress.Any, port)); listener.Start(); listener.BeginAcceptTcpClient(OnClientAccepted, listener); packets = GetComponent <PacketFactory>(); }
private void ListenForUdpData() { int errCount = 0; IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); while (udpReady) { try { byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); byte opcode = receiveBytes[0]; byte[] data = new byte[receiveBytes.Length - 1]; Array.Copy(receiveBytes, 1, data, 0, receiveBytes.Length - 1); Packet p = PacketFactory.GetPacket(opcode, data); if (p != null) { p.HandlePacket(this); } else { Debug.LogError("Unknown Opcode: " + opcode); } } catch (Exception e) { Debug.LogException(e); errCount++; if (errCount >= 3) { break; } } } }
public void Start() { Thread = new Thread(() => { try { while (true) { Utils.ReadFull(SocketStream, buffer, PacketFactory.PacketSize); IPacket header = PacketFactory.ParseHeader(buffer); chain.DoHandle(header); } } catch (ThreadAbortException) { } catch (ObjectDisposedException) { } catch (SocketException) { if (socket.Connected) { throw; } } catch (IOException e) { if (e.InnerException.GetType() != typeof(SocketException) && !socket.Connected) { return; } } finally { Dispose(); } }) { Name = string.Format("IBLVM Client handler [{0}]", socket.RemoteEndPoint.ToString()) }; Thread.Start(); }
public void TestWalkMove() { // login, create character, start game FakeNetworkClient client = HandlerTestHelper.InitializeTestEnvironment(); WalkPacket walkPacket = new WalkPacket { Speed = 11, XCoordinate = 89, YCoordinate = 126 }; // send walkpacket to client client.ReceivePacket(walkPacket); string mvPacket = HandlerTestHelper.WaitForPacket(client, "mv"); MovePacket movePacket = PacketFactory.Deserialize <MovePacket>(mvPacket); Assert.AreEqual(walkPacket.XCoordinate, movePacket.PositionX); Assert.AreEqual(walkPacket.YCoordinate, movePacket.PositionY); Assert.AreEqual(walkPacket.Speed, movePacket.Speed); HandlerTestHelper.ShutdownTestingEnvironment(); Assert.Pass(); }
public FLVFile(Stream stream) { sourceStream = stream; Size = stream.Length; DataStream ds = new DataStream(stream); ds.BigEndian = true; ds.Unsecure = true; Header = new FLVHeader(ds); while (stream.Position < stream.Length) { BasePacket packet = PacketFactory.ReadPacket(ds); if (packet.PacketType == 0 && packet.PayloadSize == 0) { if (stream.Position < stream.Length) { Console.WriteLine("Zero data detected at {0}. Integrity is unrecoverable. Dropping the rest of stream ({1} bytes remains).", stream.Position, stream.Length - stream.Position); } break; } if (packet is MetadataPacket metadataPacket) { if (Metadata != null) { Console.WriteLine("Discarding duplicate metadata packet at: {0}", metadataPacket.Offset); continue; } Metadata = metadataPacket; } Packets.Add(packet); } }
public void Setup() { TypeAdapterConfig <CharacterDto, Character> .NewConfig().ConstructUsing(src => new Character(null, null, null, null, null, null, null, _logger)); TypeAdapterConfig <MapMonsterDto, MapMonster> .NewConfig().ConstructUsing(src => new MapMonster(new List <NpcMonsterDto>(), _logger)); new Mapper(); PacketFactory.Initialize <NoS0575Packet>(); var contextBuilder = new DbContextOptionsBuilder <NosCoreContext>().UseInMemoryDatabase( databaseName: Guid.NewGuid().ToString()); DataAccessHelper.Instance.InitializeForTest(contextBuilder.Options); var map = new MapDto { MapId = 1 }; _mapDao.InsertOrUpdate(ref map); var _acc = new AccountDto { Name = "AccountTest", Password = "******".ToSha512() }; _accountDao.InsertOrUpdate(ref _acc); _chara = new Character(null, null, null, _characterRelationDao, _characterDao, _itemInstanceDao, _accountDao, _logger) { Name = "TestExistingCharacter", Slot = 1, AccountId = _acc.AccountId, MapId = 1, State = CharacterState.Active }; CharacterDto character = _chara; _characterDao.InsertOrUpdate(ref character); _session.InitializeAccount(_acc); _handler = new CharacterScreenPacketController(null, null, new Adapter(), _characterDao, _accountDao, _itemInstanceDao, _mateDao, _logger); _handler.RegisterSession(_session); }
public void GeneratePacketWithNullableOptional() { var testPacket = new NInvPacket { Items = new List <NInvItemSubPacket> { new NInvItemSubPacket { Type = 0, Slot = 0, Price = 0, RareAmount = null, UpgradeDesign = null, VNum = 0 } } }; var packet = PacketFactory.Serialize(new[] { testPacket }); Assert.AreEqual( "n_inv 0 0 0 0 0.0.0.-1.0", packet); }
private void SetupRequest(Request request) { switch (Context.ServiceContract.ConcurrencyMode) { case ConcurrencyMode.Single: case ConcurrencyMode.Reentrant: { var response = Response(request); var respPack = PacketFactory.Create(response); Session.Send(respPack); } break; case ConcurrencyMode.Multiple: ThreadPool.QueueUserWorkItem(obj => { var response = Response(request); var packet = PacketFactory.Create(response); Session.Send(packet); }, null); break; } }
public void Setup() { PacketFactory.Initialize <NoS0575Packet>(); var contextBuilder = new DbContextOptionsBuilder <NosCoreContext>().UseInMemoryDatabase( databaseName: Guid.NewGuid().ToString()); DataAccessHelper.Instance.InitializeForTest(contextBuilder.Options); var map = new MapDto { MapId = 1 }; DaoFactory.MapDao.InsertOrUpdate(ref map); _acc = new AccountDto { Name = Name, Password = EncryptionHelper.Sha512("test") }; DaoFactory.AccountDao.InsertOrUpdate(ref _acc); _session.InitializeAccount(_acc); _handler = new LoginPacketController(new LoginConfiguration()); _handler.RegisterSession(_session); WebApiAccess.RegisterBaseAdress(); WebApiAccess.Instance.MockValues = new Dictionary <string, object>(); }
/// <summary> /// Encerra o RPC conforme o resultado da finalização da task de entrada. /// Caso a task tenha sido encerrada com sucesso, o RPC é desconectado sem o envio de /// um valor de retorno, encerrando as chamadas remotas por desconexão (close). /// Caso a task tenha sido encerrada com erro, um erro RpcException é enviado /// para o ponto remoto, encerrando as chamadas remotas com erro. /// Em qualquer caso, as chamadas locais são canceladas/encerradas por desconexão. /// </summary> /// <param name="taskSend">Task de processamento do retorno do RPC</param> public void Close(Task taskSend) { if (m_State != StreamState.Open) { return; } m_State = StreamState.Closed; InternalPacket packet; Exception ex = null; if (taskSend.IsFaulted) { ex = taskSend.Exception; } else if (taskSend.IsCanceled) { ex = new OperationCanceledException(); } if (taskSend.IsFaulted || taskSend.IsCanceled) { // Failed return var rpcException = RpcExceptionFactory.CreateFrom(ex); packet = PacketFactory.NewPacket(m_MsgId, P_OPTIONS_RPC_ERROR, rpcException); } else { // Normal return packet = PacketFactory.NewPacket(m_MsgId, P_OPTIONS_RPC_CLOSE); } m_Session.TrySend(packet); m_ReturnValueTcs.TrySetCanceled(); Finish(); }
public void Shout(ShoutPacket shoutPacket) { var message = $"({Language.Instance.GetMessageFromKey(LanguageKey.ADMINISTRATOR, Session.Account.Language)}) {shoutPacket.Message}"; var sayPacket = new SayPacket { VisualType = VisualType.Player, VisualId = 0, Type = SayColorType.Yellow, Message = message }; var msgPacket = new MsgPacket { Type = MessageType.Shout, Message = message }; var sayPostedPacket = new PostedPacket { Packet = PacketFactory.Serialize(new[] { sayPacket }), SenderCharacter = new Character { Name = Session.Character.Name, Id = Session.Character.CharacterId }, ReceiverType = ReceiverType.All }; var msgPostedPacket = new PostedPacket { Packet = PacketFactory.Serialize(new[] { msgPacket }), ReceiverType = ReceiverType.All }; WebApiAccess.Instance.BroadcastPackets(new List <PostedPacket>(new[] { sayPostedPacket, msgPostedPacket })); }
public NetworkServer(ILogger logger, PacketFactory packetFactory, ProcessorManager processorManager) { this.logger = logger; bossGroup = new MultithreadEventLoopGroup(1); workerGroup = new MultithreadEventLoopGroup(); bootstrap = new ServerBootstrap() .Option(ChannelOption.SoBacklog, 100) .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .ChildHandler(new ActionChannelInitializer <IChannel>(x => { var pipeline = x.Pipeline; var client = new NetworkClient(logger, x); var session = new LoginSession(client); client.PacketReceived += packet => { var processor = processorManager.GetPacketProcessor(packet.GetType()); if (processor is null) { return(Task.CompletedTask); } return(processor.ProcessPacket(session, packet)); }; pipeline.AddLast("decoder", new Decoder(logger)); pipeline.AddLast("deserializer", new Deserializer(logger, packetFactory)); pipeline.AddLast("client", client); pipeline.AddLast("encoder", new Encoder(logger)); pipeline.AddLast("serializer", new Serializer(logger, packetFactory)); })); }
/// <summary> /// Initialize all data members. /// </summary> public OperatorTerminal(Boolean isFake = false) { this.isFake = isFake; // Set up the default window size. columnSize = (int)((float)Console.LargestWindowWidth / 2f); rowSize = (int)((float)Console.LargestWindowHeight / 1.4f); if (!isFake) { Console.SetWindowSize(columnSize + 1, rowSize + 2); } // Create the text ui instance. tui = new TextUI(rowSize, columnSize, isFake); // Default state is login. currentState = TerminalState.LOGIN; // Setup the array of updateDelegates. updateDelegates = new UpdateDelegate[(int)TerminalState.COUNT]; // Set each updateDelegate. updateDelegates[(int)TerminalState.LOGIN] = LoginUpdate; updateDelegates[(int)TerminalState.MENU] = MenuUpdate; // Initially, no user logged in. sessionID = ""; userID = ""; // Generate a server instance. server = new ChocAnServer.ChocAnServer(); // Generate a packet factory instance. packetFactory = new PacketFactory(); }
public void GeneratePacketWithDefaultSplitter() { var subpacket = new List <NsTeStSubPacket>(); subpacket.Add(new NsTeStSubPacket { Host = "-1", Port = null, Color = null, WorldCount = 10000, WorldId = 10000, Name = "1" }); var nstestpacket = new NsTestPacket { AccountName = "test", SubPacket = subpacket, SessionId = 1 }; var packet = PacketFactory.Serialize(nstestpacket); Assert.AreEqual("NsTeST test 1 -1:-1:-1:10000.10000.1", packet); }