public List <BgoProtocolReader> RecvMessage() { List <BgoProtocolReader> list = new List <BgoProtocolReader>(); try { if (!IsSocketConnected()) { throw new Exception("Connected is false"); } if (socket.Available < 4) { return(list); } needToReceive = socket.Available; while (true) { BgoProtocolReader bgoProtocolReader = RecvCurrentMessage(); if (bgoProtocolReader == null) { break; } list.Add(bgoProtocolReader); } return(list); } catch (Exception arg) { //Disconnect("Error receiving: " + arg); CloseClient(); return(list); } }
private BgoProtocolReader RecvCurrentMessage() { if (needToReceive < 4) { return(null); } if (!isReadLength) { byte[] array = new byte[2]; int num = socket.Receive(array, 0, array.Length, SocketFlags.None); needToReceive -= num; debugReceiveData += (uint)array.Length; if (num != 2) { throw new Exception("receive length != 2"); } packetLength = BgoProtocolReader.ReadBufferSize(array); isReadLength = true; } if (packetLength <= socket.Available) { byte[] array2 = new byte[packetLength]; debugReceiveDataMax = Math.Max(debugReceiveDataMax, (uint)packetLength); int num2 = socket.Receive(array2, 0, array2.Length, SocketFlags.None); needToReceive -= num2; debugReceiveData += (uint)array2.Length; if (num2 != packetLength) { throw new Exception("receive length != packet lenght"); } isReadLength = false; return(new BgoProtocolReader(array2)); } return(null); }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = br.ReadUInt16(); switch ((Request)msgType) { case Request.Command: switch (br.ReadString()) { case "sector_op": string soFaction = br.ReadString(); string soAddPoints = br.ReadString(); Faction soRealFaction = soFaction == "colonial" ? Faction.Colonial : Faction.Cylon; Server.GetSectorByClientIndex(index).SetOutpost(soRealFaction, int.Parse(soAddPoints)); break; } break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
private void DebugMessage(BgoProtocolWriter w) { BgoProtocolReader buffer = new BgoProtocolReader(w.GetBuffer()); buffer.ReadUInt16(); byte protocolId = buffer.ReadByte(); Log.Add(LogSeverity.INFO, Log.LogDir.Out, string.Format("Protocol ID: {0} ({1}) - msgType: {2}", protocolId, (ProtocolID)protocolId, buffer.ReadUInt16())); }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = (ushort)br.ReadUInt16(); switch ((Request)msgType) { // This case is ran when the player selects his faction. It will send to the client an // empty Avatar Description, so the customization will be set to default, and sends back // the faction, so the game will be sure that the selected faction is real. Also fater that // we change the scene to Avatar. case Request.SelectFaction: SendNewAvatarDescription(index); SendFaction(index, (Faction)br.ReadByte()); Server.GetClientByIndex(index).Character.GameLocation = GameLocation.Avatar; break; // Since we are not using a real database yet, we can just use the fake database to check if // the name is available or not. case Request.CheckNameAvailability: SendNameAvailability(index, br.ReadString()); break; case Request.ChooseName: Server.GetClientByIndex(index).Character.name = br.ReadString(); SendName(index); break; case Request.CreateAvatar: Dictionary <AvatarItem, string> items = new Dictionary <AvatarItem, string>(); int num = br.ReadLength(); for (int i = 0; i < num; i++) { items[(AvatarItem)br.ReadByte()] = br.ReadString(); } Client client = Server.GetClientByIndex(index); Database.Database.CreateCharacter(client.Character.name, client.playerId.ToString(), (byte)client.Character.Faction, items); Server.GetClientByIndex(index).Character.items = items; SendAvatar(index); SendPlayerId(index); SendPlayerShips(index, 100, (uint)22131177); Server.GetClientByIndex(index).Character.GameLocation = GameLocation.Space; break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = (ushort)br.ReadUInt16(); switch ((Request)msgType) { default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
private void ReceiveCallback(IAsyncResult ar) { try { int received = socket.EndReceive(ar); if (received <= 0) { CloseClient(index); } else { byte[] databuffer = new byte[received]; Buffer.BlockCopy(_buffer, 0, databuffer, 0, received); byte[] incomingMsg = new byte[2]; incomingMsg[0] = databuffer[0]; incomingMsg[1] = databuffer[1]; ushort packetLength = (ushort)(BgoProtocolReader.ReadBufferSize(incomingMsg) + 2); byte[] parsedArray = new byte[packetLength]; Array.Copy(databuffer, 0, parsedArray, 0, packetLength); // The first packet should always be right. ProtocolManager.HandleNetworkInformation(index, parsedArray); // If the first packet length isn't equal the received buffer length, then it received more than // one packet on the buffer and it should be parsed to avoid any kind of problem. // That's how Async works xd. There might be a better solution but this is what I could do. if (packetLength != databuffer.Length) { ushort prevPacketLength = 0; while (prevPacketLength + packetLength != databuffer.Length) { prevPacketLength += packetLength; incomingMsg = new byte[2]; incomingMsg[0] = databuffer[prevPacketLength + 0]; incomingMsg[1] = databuffer[prevPacketLength + 1]; packetLength = (ushort)(BgoProtocolReader.ReadBufferSize(incomingMsg) + 2); parsedArray = new byte[packetLength]; Array.Copy(databuffer, prevPacketLength, parsedArray, 0, packetLength); ProtocolManager.HandleNetworkInformation(index, parsedArray); } } socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket); } } catch (Exception ex) { Log.Add(LogSeverity.ERROR, "Exception thrown " + ex); CloseClient(index); } }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = (ushort)br.ReadUInt16(); switch ((Request)msgType) { case Request.Init: SendInit(index); break; case Request.Player: // This is the ConnectType, but we aren't checking for that yet ConnectType connectType = (ConnectType)br.ReadByte(); // Check if the player exists on our database. We'll have checks for client connected later, but it's // not necessary yet uint playerId = br.ReadUInt32(); string playerName = br.ReadString(); string sessionCode = br.ReadString(); switch (connectType) { case ConnectType.Web: if (Database.Database.CheckSessionCodeExistance(sessionCode)) { playerId = uint.Parse(Database.Database.GetUserBySession(sessionCode).PlayerId); Server.GetClientByIndex(index).playerId = playerId; Server.GetClientByIndex(index).Character = new Character(index); SendPlayer(index); if (Database.Database.CheckCharacterExistanceById(playerId.ToString())) { } } else { SendError(index, (byte)LoginError.WrongSession); } break; default: Log.Add(LogSeverity.ERROR, "Unknown Connection Type " + connectType + " on Login Protocol"); break; } break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = br.ReadUInt16(); switch ((Request)msgType) { case Request.Info: uint playerId = br.ReadUInt32(); uint flags = br.ReadUInt32(); Console.WriteLine("Info: PlayerId {0} flags {1}", playerId, flags); SendName(index, playerId); SendFaction(index, playerId); SendPlayerAvatar(index, playerId); SendPlayerLevel(index, playerId); SendPlayerStatus(index, playerId, true); CatalogueProtocol.GetProtocol().SendCard(index, CardView.GUI, (uint)Server.GetClientByPlayerId(playerId.ToString()).index); switch (flags) { default: Log.Add(LogSeverity.ERROR, "Unknown flag " + flags + " on Subscribe Info"); break; } break; case Request.Subscribe: uint playerId2 = br.ReadUInt32(); uint flags2 = br.ReadUInt32(); Console.WriteLine("Subscribe: PlayerId {0} flags {1}", playerId2, flags2); switch (flags2) { default: Log.Add(LogSeverity.ERROR, "Unknown flag " + flags2 + " on Subscribe Info"); break; } break; case Request.SubscribeStats: uint playerId3 = br.ReadUInt32(); Console.WriteLine("SubscribeStats: PlayerId {0}", playerId3); break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort messageId = br.ReadUInt16(); ushort uiElement = br.ReadUInt16(); switch (messageId) { case 0: Log.Add(LogSeverity.INFO, string.Format("The element {0} is shown.", (UiElementId)uiElement)); break; case 1: Log.Add(LogSeverity.INFO, string.Format("The element {0} is hidden.", (UiElementId)uiElement)); break; } }
private void ReadProperty(IDictionary <UserSetting, object> settings, BgoProtocolReader br) { UserSetting property = (UserSetting)br.ReadByte(); UserSettingValueType valueType = (UserSettingValueType)br.ReadByte(); switch (valueType) { case UserSettingValueType.Byte: settings.Add(property, br.ReadByte()); break; case UserSettingValueType.Float: settings.Add(property, br.ReadSingle()); break; case UserSettingValueType.Boolean: settings.Add(property, br.ReadBoolean()); break; case UserSettingValueType.Integer: settings.Add(property, br.ReadInt32()); break; case UserSettingValueType.Float2: { settings.Add(property, new float2(br.ReadSingle(), br.ReadSingle())); break; } case UserSettingValueType.HelpScreenType: { List <HelpScreenType> hstList = new List <HelpScreenType>(); int hstSize = br.ReadUInt16(); for (int i = 0; i < hstSize; i++) { hstList.Add((HelpScreenType)br.ReadUInt16()); } settings.Add(property, hstList); break; } default: settings.Add(property, br.ReadByte()); break; } }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = br.ReadUInt16(); switch ((Request)msgType) { case Request.SaveSettings: IDictionary <UserSetting, object> settings = new Dictionary <UserSetting, object>(); int num = br.ReadUInt16(); for (int i = 0; i < num; i++) { ReadProperty(settings, br); } Server.GetClientByIndex(index).Character.settings = settings; Database.Database.SaveSettings(Server.GetClientByIndex(index).playerId.ToString(), settings); break; case Request.SaveKeys: List <string> controlKeys = new List <string>(); int num2 = br.ReadUInt16(); for (int j = 0; j < num2; j++) { ushort deviceTriggerCode = br.ReadUInt16(); ushort action = br.ReadUInt16(); byte deviceModifierCode = br.ReadByte(); byte device = br.ReadByte(); byte flags = br.ReadByte(); byte profileNo = br.ReadByte(); controlKeys.Add(deviceTriggerCode + "|" + action + "|" + deviceModifierCode + "|" + device + "|" + flags + "|" + profileNo); } Server.GetClientByIndex(index).Character.controlKeys = controlKeys; Database.Database.SaveKeys(Server.GetClientByIndex(index).playerId.ToString(), controlKeys); break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = br.ReadUInt16(); switch ((Request)msgType) { case Request.QuitLogin: SendLoadNextScene(index); break; case Request.SceneLoaded: SceneLoaded(index); break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
public static void HandleNetworkInformation(int index, BgoProtocolReader buffer) { byte b = buffer.ReadByte(); Log.Add(LogSeverity.INFO, Log.LogDir.In, string.Format("Protocol ID: {0} ({1})", b, (Protocol.ProtocolID)b)); try { GetProtocol((Protocol.ProtocolID)b).ParseMessage(index, buffer); } catch (Exception ex) { string text = "Couldn't handle message for " + (Protocol.ProtocolID)b + " Protocol (msgType:" + buffer.ReadUInt16() + "). "; if (GetProtocol((Protocol.ProtocolID)b) == null) { text = text + b + " Protocol is not (any more) registered. "; } text = text + "\nCaught Exception: " + ex.ToString(); Log.Add(LogSeverity.ERROR, text); } buffer.Dispose(); }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = (ushort)br.ReadUInt16(); switch ((Request)msgType) { // I'm not sure if the JumpIn request did send the WhoIs of the player, but it works I guess. // Also I don't know if it was sent to everyone or just to the client. Probably everyone on the sector, // but since we are doing this offline for now, let's keep it still only client. case Request.JumpIn: SendWhoIsPlayer(index); SetTimeOrigin(index); PlayerProtocol.GetProtocol().SendStats(index); // These are the stats of your ship, not the base ones. SyncMove(index, SpaceEntityType.Player, (uint)index, new Vector3(0, 100f, 100f)); break; case Request.CompleteJump: PlayerProtocol.GetProtocol().SendUnanchor(index); StoryProtocol.GetProtocol().EnableGear(index, true); break; case Request.SetSpeed: byte mode = br.ReadByte(); float speed = br.ReadSingle(); Server.GetClientByIndex(index).Character.shipMode = mode; Server.GetClientByIndex(index).Character.shipSpeed = speed; SyncMove(index, SpaceEntityType.Player, (uint)index); break; case Request.WASD: Server.GetClientByIndex(index).Character.qweasd = br.ReadByte(); SyncMove(index, SpaceEntityType.Player, (uint)index); break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = br.ReadUInt16(); switch ((Request)msgType) { case Request.SubscribeGalaxyMap: uint[] sectorIds = new uint[Server.Sectors.Count]; int num = 0; foreach (Sector sector in Server.Sectors) { sectorIds[num] = sector.sectorId; num++; } SendSectorPlayerSlotsToPlayer(index, sectorIds, Server.GetClientByIndex(index).Character.Faction, SectorSlotCapType.Total); break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
public static void HandleNetworkInformation(int index, byte[] data) { BgoProtocolReader buffer = new BgoProtocolReader(data); buffer.ReadUInt16(); byte protocolID = buffer.ReadByte(); Log.Add(LogSeverity.INFO, Log.LogDir.In, string.Format("Protocol ID: {0} ({1})", protocolID, (Protocol.ProtocolID)protocolID)); try { GetProtocol((Protocol.ProtocolID)protocolID).ParseMessage(index, buffer); } catch (Exception ex) { string text = ""; try { text += "Couldn't handle message for " + (Protocol.ProtocolID)protocolID + " Protocol"; } catch { } try { text += " (msgType: " + buffer.ReadUInt16() + "). "; } catch { } if (GetProtocol((Protocol.ProtocolID)protocolID) == null) { text = text + protocolID + " Protocol is not (any more) registered. "; } text = text + "\nCaught Exception: " + ex; Log.Add(LogSeverity.ERROR, text); } }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = br.ReadUInt16(); switch (msgType) { case 1: ushort num = br.ReadUInt16(); for (int i = 0; i < num; i++) { uint key = br.ReadUInt32(); ushort value = br.ReadUInt16(); SendCard(index, value, key); } break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", msgType, protocolID)); break; } }
private void HandleConnection() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = tokenSource.Token; Task.Factory.StartNew(delegate { while (!cancellationToken.IsCancellationRequested) { bool lockTaken = false; try { Monitor.Enter(socket, ref lockTaken); if (socket != null && socket.Connected) { if (socket.Poll(1000, SelectMode.SelectRead)) { byte[] buffer = new byte[1]; if (socket.Receive(buffer, SocketFlags.Peek) == 0) { throw new Exception("The socket has been closed"); } byte[] array = new byte[2]; if (socket.Receive(array, 0, array.Length, SocketFlags.None) != 2) { throw new Exception("Error receiving: packetLenght != 4"); } int num = BgoProtocolReader.ReadBufferSize(array); byte[] array2 = new byte[num]; if (socket.Receive(array2, 0, array2.Length, SocketFlags.None) != num) { throw new Exception("Error receiving: receive length != packet length"); } BgoProtocolReader buffer2 = new BgoProtocolReader(array2); ProtocolManager.HandleNetworkInformation(index, buffer2); } } else { tokenSource.Cancel(); tokenSource.Dispose(); } } catch (Exception ex) { try { Console.WriteLine("Exception: " + ex.Message); Log.Add(LogSeverity.INFO, string.Format("Connection from {0} has been terminated.", ip)); Server.GetSectorById(Character.PlayerShip.sectorId).LeaveSector(this, RemovingCause.JustRemoved); socket.Shutdown(SocketShutdown.Both); socket.Close(); closing = true; Character = null; Server.Clients.Remove(index); } finally { if (socket != null) { socket.Dispose(); } } } finally { if (lockTaken) { Monitor.Exit(socket); } } } }, cancellationToken).ContinueWith(delegate(Task x) { x.Dispose(); }); }
public override void ParseMessage(int index, BgoProtocolReader br) { ushort msgType = br.ReadUInt16(); switch ((Request)msgType) { case Request.JumpIn: Client c = Server.GetClientByIndex(index); Server.GetSectorById(c.Character.PlayerShip.sectorId).JoinSector(c); break; case Request.CompleteJump: PlayerProtocol.GetProtocol().SendUnanchor(index, Server.GetObjectId(index)); StoryProtocol.GetProtocol().EnableGear(index, true); Server.GetClientByIndex(index).Character.PlayerShip.isVisible = false; SendChangeVisibility(index, Server.GetObjectId(index), Server.GetClientByIndex(index).Character.PlayerShip.isVisible, 0); Server.GetClientByIndex(index).Character.PlayerShip.jumpInTime = DateTime.Now.AddSeconds(10); break; case Request.SetSpeed: Client setSpeedClient = Server.GetClientByIndex(index); CheckIfVisibleAndSetIfNot(setSpeedClient); byte mode = br.ReadByte(); float speed = br.ReadSingle(); setSpeedClient.Character.PlayerShip.shipMode = mode; setSpeedClient.Character.PlayerShip.shipSpeed = speed; setSpeedClient.Character.PlayerShip.MovementOptions.speed = setSpeedClient.Character.PlayerShip.shipGear == Gear.Regular ? setSpeedClient.Character.PlayerShip.shipSpeed : setSpeedClient.Character.PlayerShip.currentShipStats.BoostSpeed; SyncMove(index, SpaceEntityType.Player, Server.GetObjectId(index)); break; case Request.SetGear: Client setGearClient = Server.GetClientByIndex(index); CheckIfVisibleAndSetIfNot(setGearClient); setGearClient.Character.PlayerShip.shipGear = (Gear)br.ReadByte(); setGearClient.Character.PlayerShip.MovementOptions.speed = setGearClient.Character.PlayerShip.shipGear == Gear.Regular ? setGearClient.Character.PlayerShip.shipSpeed : setGearClient.Character.PlayerShip.currentShipStats.BoostSpeed; SyncMove(index, SpaceEntityType.Player, Server.GetObjectId(index)); break; case Request.WASD: Client wasdClient = Server.GetClientByIndex(index); Sector wasdServer = Server.GetSectorById(wasdClient.Character.PlayerShip.sectorId); CheckIfVisibleAndSetIfNot(wasdClient); wasdClient.Character.PlayerShip.qweasd.Bitmask = br.ReadByte(); wasdClient.Character.PlayerShip.ManeuverController.AddManeuver(new TurnManeuver(ManeuverType.Turn, wasdServer.Tick.Current.value, wasdClient.Character.PlayerShip.qweasd, wasdClient.Character.PlayerShip.MovementOptions)); SyncMove(index, SpaceEntityType.Player, Server.GetObjectId(index)); break; case Request.MoveToDirection: Client directionalClient = Server.GetClientByIndex(index); Sector directionalServer = Server.GetSectorById(directionalClient.Character.PlayerShip.sectorId); CheckIfVisibleAndSetIfNot(directionalClient); directionalClient.Character.PlayerShip.direction = br.ReadEuler(); directionalClient.Character.PlayerShip.ManeuverController.AddManeuver(new DirectionalManeuver(ManeuverType.Directional, directionalServer.Tick.Current.value, directionalClient.Character.PlayerShip.direction, directionalClient.Character.PlayerShip.MovementOptions)); SyncMove(index, SpaceEntityType.Player, Server.GetObjectId(index)); break; case Request.MoveToDirectionWithoutRoll: Client directionalWrClient = Server.GetClientByIndex(index); Sector directionalWrServer = Server.GetSectorById(directionalWrClient.Character.PlayerShip.sectorId); CheckIfVisibleAndSetIfNot(directionalWrClient); directionalWrClient.Character.PlayerShip.direction = br.ReadEuler(); directionalWrClient.Character.PlayerShip.ManeuverController.AddManeuver(new DirectionalWithoutRollManeuver(ManeuverType.DirectionalWithoutRoll, directionalWrServer.Tick.Current.value, directionalWrClient.Character.PlayerShip.direction, directionalWrClient.Character.PlayerShip.MovementOptions)); SyncMove(index, SpaceEntityType.Player, Server.GetObjectId(index)); break; case Request.QWEASD: Client qweasdClient = Server.GetClientByIndex(index); Sector qweasdServer = Server.GetSectorById(qweasdClient.Character.PlayerShip.sectorId); CheckIfVisibleAndSetIfNot(qweasdClient); qweasdClient.Character.PlayerShip.qweasd.Bitmask = br.ReadByte(); qweasdClient.Character.PlayerShip.ManeuverController.AddManeuver(new TurnQweasdManeuver(ManeuverType.TurnQweasd, qweasdServer.Tick.Current.value, qweasdClient.Character.PlayerShip.qweasd, qweasdClient.Character.PlayerShip.MovementOptions)); SyncMove(index, SpaceEntityType.Player, Server.GetObjectId(index)); break; case Request.Dock: uint objId = br.ReadUInt32(); float delay = br.ReadSingle(); SendDock(index, delay); break; case Request.Quit: Client quitClient = Server.GetClientByIndex(index); quitClient.Character.PlayerShip.isSpawned = false; if (quitClient.Character.PlayerShip.requestedJumpSectorId == -1) { quitClient.Character.GameLocation = GameLocation.Room; } else { quitClient.Character.PlayerShip.requestedJumpSectorId = -1; Database.Database.SaveSector(quitClient.playerId.ToString(), quitClient.Character.PlayerShip.sectorId); quitClient.Character.GameLocation = GameLocation.Space; quitClient.Character.PlayerShip.shipGear = Gear.Regular; quitClient.Character.PlayerShip.shipSpeed = 0; } break; case Request.Jump: Client jumpClient = Server.GetClientByIndex(index); CheckIfVisibleAndSetIfNot(jumpClient); SendJump(index, br.ReadUInt32(), true); break; case Request.StopJump: Client stopJumpClient = Server.GetClientByIndex(index); if (stopJumpClient.Character.PlayerShip.requestedJumpSectorId != -1) { SendStopJump(index); } break; default: Log.Add(LogSeverity.ERROR, string.Format("Unknown msgType \"{0}\" on {1}Protocol.", (Request)msgType, protocolID)); break; } }
public virtual void ParseMessage(int index, BgoProtocolReader br) { }
public void Read(BgoProtocolReader pr) { value = pr.ReadInt32(); }
public abstract void ParseMessage(int index, BgoProtocolReader br);