void Start() { // The current state is Login State = ChatStates.Login; // Change an option to show how it should be done SocketOptions options = new SocketOptions(); options.AutoConnect = false; // Create the Socket.IO manager Manager = new SocketManager(new Uri("http://chat.socket.io/socket.io/"), options); // Set up custom chat events Manager.Socket.On("login", OnLogin); Manager.Socket.On("new message", OnNewMessage); Manager.Socket.On("user joined", OnUserJoined); Manager.Socket.On("user left", OnUserLeft); Manager.Socket.On("typing", OnTyping); Manager.Socket.On("stop typing", OnStopTyping); // The argument will be an Error object. Manager.Socket.On(SocketIOEventTypes.Error, (socket, packet, args) => Debug.LogError(string.Format("Error: {0}", args[0].ToString()))); // We set SocketOptions' AutoConnect to false, so we have to call it manually. Manager.Open(); }
void Start() { // Change an option to show how it should be done SocketOptions options = new SocketOptions(); options.AutoConnect = false; // Create the SocketManager instance var manager = new SocketManager(new Uri("http://io.weplay.io/socket.io/"), options); // Keep a reference to the root namespace Socket = manager.Socket; // Set up our event handlers. Socket.On(SocketIOEventTypes.Connect, OnConnected); Socket.On("joined", OnJoined); Socket.On("connections", OnConnections); Socket.On("join", OnJoin); Socket.On("move", OnMove); Socket.On("message", OnMessage); Socket.On("reload", OnReload); // Don't waste cpu cycles on decoding the payload, we are expecting only binary data with this event, // and we can access it through the packet's Attachments property. Socket.On("frame", OnFrame, /*autoDecodePayload:*/ false); // Add error handler, so we can display it Socket.On(SocketIOEventTypes.Error, OnError); // We set SocketOptions' AutoConnect to false, so we have to call it manually. manager.Open(); // We are connecting to the server. State = States.Connecting; }
// Use this for initialization void Start () { if (ins == null) ins = this; netEvents = new Dictionary<string, Action<NadEvent>>(); Test test = new Test(); test.addEventListener(); Debug.Log("Test Event Listener..."); Events evt = new Events(); evt.setType(Events.LOG_IN); this.dispatchEvent(evt); ConnectToServer(); }
private void Initialize(IPEndPoint here, int generation, IMessagingConfiguration config, ISiloPerformanceMetrics metrics = null) { if(log.IsVerbose3) log.Verbose3("Starting initialization."); SocketManager = new SocketManager(config); ima = new IncomingMessageAcceptor(this, here, SocketDirection.SiloToSilo); MyAddress = SiloAddress.New((IPEndPoint)ima.AcceptingSocket.LocalEndPoint, generation); MessagingConfiguration = config; InboundQueue = new InboundMessageQueue(); OutboundQueue = new OutboundMessageQueue(this, config); Gateway = null; Metrics = metrics; sendQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_SEND_QUEUE_LENGTH, () => SendQueueLength); receiveQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_RECEIVE_QUEUE_LENGTH, () => ReceiveQueueLength); if (log.IsVerbose3) log.Verbose3("Completed initialization."); }
public virtual void Start() { m_PUUID = 0; m_IsUpdate = false; m_pPU = null; m_pProcessUnit = null; m_pProcessUnitBank = new ProcessUnitBank(); do{ m_pSocketManager = new SocketManager(); if ( null == m_pSocketManager ){ Logger.MLNLOG_ERR("Error SocketManager"); break; } if ( SocketManager.SOCKETMANAGER_RET_CODE.ERROR == m_pSocketManager.Initialize() ){ Logger.MLNLOG_ERR( "Error SocketManager Initialize" ); break; } m_PUUID = CreatePU(); if (ProcessUnitManager.INVALID_PUUID == m_PUUID) { Logger.MLNLOG_ERR("Error CreatePU"); m_IsUpdate = false; break; } m_pProcessUnit = m_pProcessUnitBank.GetProcessUnitFromId(m_PUUID); m_pPU = (BTL.PU_Client)m_pProcessUnit as BTL.PU_Client; m_pPU.Start(); m_pPU.SetCharaId( m_CharaId ); m_pPU.GetRpcConnector().SetSocketManager(m_pSocketManager); m_pPU.GetRpcConnector().SetProcessUnit(m_pProcessUnitBank.GetProcessUnitFromId(m_PUUID)); m_pPU.GetRpcConnector().SetProcessUnitBank(m_pProcessUnitBank); m_pPU.GetRpcConnector().NewRelayConnector(); m_IsUpdate = true; }while ( false ); }
private void OnDisable() { SocketManager.ListenDelegate(false, messageHandle, OperationListenInfo); }
private (string, object[]) ReadData(SocketManager manager, IncomingPacket packet, IJsonReader reader) { Socket socket = manager.GetSocket(packet.Namespace); string eventName = packet.EventName; Subscription subscription = socket.GetSubscription(eventName); object[] args = null; switch (packet.SocketIOEvent) { case SocketIOEventTypes.Unknown: // TODO: Error? break; case SocketIOEventTypes.Connect: // No Data | Object args = ReadParameters(socket, subscription, reader); //SkipObject(reader); break; case SocketIOEventTypes.Disconnect: // No Data break; case SocketIOEventTypes.Error: // String | Object switch (reader.Token) { case JsonToken.StringLiteral: args = new object[] { new Error(reader.ReadString()) }; break; case JsonToken.BeginObject: args = ReadParameters(socket, subscription, reader); break; } break; case SocketIOEventTypes.Ack: eventName = IncomingPacket.GenerateAcknowledgementNameFromId(packet.Id); subscription = socket.GetSubscription(eventName); reader.ReadArrayBegin(); args = ReadParameters(socket, subscription, reader); reader.ReadArrayEnd(); break; default: // Array reader.ReadArrayBegin(); eventName = reader.ReadString(); subscription = socket.GetSubscription(eventName); args = ReadParameters(socket, subscription, reader); reader.ReadArrayEnd(); break; } return(eventName, args); }
partial void OnCreateReaderWriter(ConfigurationOptions configuration) { ownsSocketManager = configuration.SocketManager == null; socketManager = configuration.SocketManager ?? new SocketManager(ClientName, configuration.HighPrioritySocketThreads); }
public PollingTransport(SocketManager manager) { Manager = manager; }
public Form1(SocketManager socketManager) { InitializeComponent(); this.socketManager = socketManager; }
private bool SendBatch(List <Message> msgs, Socket sock) { if (Cts.IsCancellationRequested) { return(false); } if (sock == null) { return(false); } if (msgs == null || msgs.Count == 0) { return(true); } // Send the message List <ArraySegment <byte> > data; int headerLengths; bool continueSend = OutgoingMessageSender.SerializeMessages(msgs, out data, out headerLengths, OnMessageSerializationFailure); if (!continueSend) { return(false); } int length = data.Sum(x => x.Count); int bytesSent = 0; bool exceptionSending = false; bool countMismatchSending = false; string sendErrorStr; try { bytesSent = sock.Send(data); if (bytesSent != length) { // The complete message wasn't sent, even though no error was reported; treat this as an error countMismatchSending = true; sendErrorStr = String.Format("Byte count mismatch on send: sent {0}, expected {1}", bytesSent, length); Log.Warn(ErrorCode.GatewayByteCountMismatch, sendErrorStr); } } catch (Exception exc) { exceptionSending = true; string remoteEndpoint = ""; if (!(exc is ObjectDisposedException)) { remoteEndpoint = sock.RemoteEndPoint.ToString(); } sendErrorStr = String.Format("Exception sending to client at {0}: {1}", remoteEndpoint, exc); Log.Warn(ErrorCode.GatewayExceptionSendingToClient, sendErrorStr, exc); } MessagingStatisticsGroup.OnMessageBatchSend(msgs[0].TargetSilo, msgs[0].Direction, bytesSent, headerLengths, SocketDirection.GatewayToClient, msgs.Count); bool sendError = exceptionSending || countMismatchSending; if (sendError) { gateway.RecordClosedSocket(sock); SocketManager.CloseSocket(sock); } gatewaySends.Increment(); foreach (Message msg in msgs) { msg.ReleaseBodyAndHeaderBuffers(); } return(!sendError); }
private void OnDisable() { SocketManager.ListenDelegate(false, messageHandleTCP, OperationListenInfoTCP); UDPManager.ListenDelegate(false, messageHandleUDP, OperationListenInfoUDP); }
public WebSocketTransport(SocketManager manager) { State = TransportStates.Closed; Manager = manager; }
private void Awake() { mSocketManager = new SocketManager(this); }
private void Start() { SocketManager.ListenDelegate(true, messageHandleTCP, OperationListenInfoTCP); UDPManager.ListenDelegate(true, messageHandleUDP, OperationListenInfoUDP); }
protected TestBase() { socketManager = new SocketManager(GetType().Name); }
public virtual void initState(ResponseBase res) { SocketManager.Instance().resDelegate = responseString; }
public static void Main() { // preliminary tests Console.WriteLine("Running preliminary tests..."); // testing unkown card equality Card unknownCard = new UnknownCard(); Card card = new UnitCard(0, "Test Card", Faction.NONE, "Some text", "Some more text", 0, 0, 0, new AbilityList()); Console.WriteLine("Testing UnknownCard == Card: {0}", unknownCard == card ? "Success" : "Fail"); // testing cardloader CardLoader cl = new CardLoader(); Card c = cl.GetByID("Mercenary Phantasm"); Console.WriteLine("Successfully Loaded Card."); // BEGIN NETWORKING //find local IP IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddr = ipEntry.AddressList[0]; //consts string HostName = ipAddr.ToString(); //by default, is using same local IP addr as server; assuming above process is deterministic const int Port = 4011; //setup the connection Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(HostName, Port); SocketManager socketManager = new SocketManager(socket, "</file>"); //setup game objects GameManager gm; Player localPlayer; //join a game and do all the setup Console.WriteLine("Press Enter to join a game..."); Console.ReadLine(); socketManager.Send("<file type='joinMatch'><deck id='myxorStarter'/></file>"); // get the matchStart message Console.WriteLine("Waiting for match start..."); XmlDocument matchStartDoc; do { matchStartDoc = socketManager.ReceiveXml(); }while(matchStartDoc == null); // init the gamestate accordingly Console.WriteLine("Initializing game state..."); int localPlayerIndex = 0; List <XmlElement> playerIds = new List <XmlElement>(); foreach (XmlElement e in matchStartDoc.GetElementsByTagName("playerIds")) { if (e.Attributes["side"].Value == "local") { localPlayerIndex = playerIds.Count; } playerIds.Add(e); } List <XmlElement> laneIds = new List <XmlElement>(); foreach (XmlElement e in matchStartDoc.GetElementsByTagName("laneIds")) { laneIds.Add(e); } gm = new GameManager(playerIds: playerIds.ToArray(), laneIds: laneIds.ToArray()); localPlayer = gm.Players[localPlayerIndex]; // get the turnStart message Console.WriteLine("Waiting for turn start..."); XmlDocument turnStartDoc; do { turnStartDoc = socketManager.ReceiveXml(); }while(turnStartDoc == null); Console.WriteLine("Applying turn start deltas..."); ProcessDeltas(turnStartDoc, cl, true); // print the gamestate foreach (Player p in gm.Players) { Console.WriteLine("\n{0} player has hand: {1}\n...deck: {2}\n", p == localPlayer? "Local" : "Enemy", p.Hand, p.Deck); } for (int i = 0; i < 10; i++) { // send a game action Console.WriteLine("Press Enter to send a Player Action..."); Console.ReadLine(); XmlDocument playerActionDoc = MessageHandler.NewEmptyMessage("gameAction"); XmlElement playerActionElement = new PlayUnitCardAction(localPlayer.Hand[0] as UnitCard, gm.Lanes[0], 0, 0).ToXml(playerActionDoc); playerActionDoc.DocumentElement.AppendChild(playerActionElement); playerActionElement = new PlayUnitCardAction(localPlayer.Hand[1] as UnitCard, gm.Lanes[0], 0, 1).ToXml(playerActionDoc); playerActionDoc.DocumentElement.AppendChild(playerActionElement); socketManager.SendXml(playerActionDoc); SimpleGetResponse(socketManager, true); // end the turn and get back the end of turn deltas Console.WriteLine("Press Enter to end turn..."); Console.Read(); socketManager.Send("<file type='lockInTurn'></file>"); Console.WriteLine("Waiting for response from server..."); SimpleGetResponse(socketManager, true); } // end the test Console.WriteLine("Press Enter to disconnect..."); Console.ReadLine(); }
public IncomingPacket Parse(SocketManager manager, string from) { int idx = 0; var transportEvent = (TransportEventTypes)ToInt(from[idx++]); var socketIOEvent = SocketIOEventTypes.Unknown; var nsp = string.Empty; var id = -1; var payload = string.Empty; int attachments = 0; if (from.Length > idx && ToInt(from[idx]) >= 0) { socketIOEvent = (SocketIOEventTypes)ToInt(from[idx++]); } else { socketIOEvent = SocketIOEventTypes.Unknown; } // Parse Attachment if (socketIOEvent == SocketIOEventTypes.BinaryEvent || socketIOEvent == SocketIOEventTypes.BinaryAck) { int endIdx = from.IndexOf('-', idx); if (endIdx == -1) { endIdx = from.Length; } int.TryParse(from.Substring(idx, endIdx - idx), out attachments); idx = endIdx + 1; } // Parse Namespace if (from.Length > idx && from[idx] == '/') { int endIdx = from.IndexOf(',', idx); if (endIdx == -1) { endIdx = from.Length; } nsp = from.Substring(idx, endIdx - idx); idx = endIdx + 1; } else { nsp = "/"; } // Parse Id if (from.Length > idx && ToInt(from[idx]) >= 0) { int startIdx = idx++; while (from.Length > idx && ToInt(from[idx]) >= 0) { idx++; } int.TryParse(from.Substring(startIdx, idx - startIdx), out id); } // What left is the payload data if (from.Length > idx) { payload = from.Substring(idx); } else { payload = string.Empty; } return(new IncomingPacket(transportEvent, socketIOEvent, nsp, id) { DecodedArg = payload, AttachementCount = attachments }); }
private void Setup() { socketManager = new SocketManager(); resourceManager = new ResourceManager(); }
public void Connect() { if (!MsgCenter.Running) { if (Log.IsVerbose) { Log.Verbose(ErrorCode.ProxyClient_MsgCtrNotRunning, "Ignoring connection attempt to gateway {0} because the proxy message center is not running", Address); } return; } // Yes, we take the lock around a Sleep. The point is to ensure that no more than one thread can try this at a time. // There's still a minor problem as written -- if the sending thread and receiving thread both get here, the first one // will try to reconnect. eventually do so, and then the other will try to reconnect even though it doesn't have to... // Hopefully the initial "if" statement will prevent that. lock (Lockable) { if (!IsLive) { if (Log.IsVerbose) { Log.Verbose(ErrorCode.ProxyClient_DeadGateway, "Ignoring connection attempt to gateway {0} because this gateway connection is already marked as non live", Address); } return; // if the connection is already marked as dead, don't try to reconnect. It has been doomed. } for (var i = 0; i < ProxiedMessageCenter.CONNECT_RETRY_COUNT; i++) { try { if (Socket != null) { if (Socket.Connected) { return; } MarkAsDisconnected(Socket); // clean up the socket before reconnecting. } if (lastConnect != new DateTime()) { // We already tried at least once in the past to connect to this GW. // If we are no longer connected to this GW and it is no longer in the list returned // from the GatewayProvider, consider directly this connection dead. if (!MsgCenter.GatewayManager.GetLiveGateways().Contains(Address)) { break; } // Wait at least ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY before reconnection tries var millisecondsSinceLastAttempt = DateTime.UtcNow - lastConnect; if (millisecondsSinceLastAttempt < ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY) { var wait = ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY - millisecondsSinceLastAttempt; if (Log.IsVerbose) { Log.Verbose(ErrorCode.ProxyClient_PauseBeforeRetry, "Pausing for {0} before trying to connect to gateway {1} on trial {2}", wait, Address, i); } Thread.Sleep(wait); } } lastConnect = DateTime.UtcNow; Socket = new Socket(Silo.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); SocketManager.Connect(Socket, Silo.Endpoint, this.openConnectionTimeout); NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket(); MsgCenter.OnGatewayConnectionOpen(); SocketManager.WriteConnectionPreamble(Socket, MsgCenter.ClientId); // Identifies this client Log.Info(ErrorCode.ProxyClient_Connected, "Connected to gateway at address {0} on trial {1}.", Address, i); return; } catch (Exception ex) { Log.Warn(ErrorCode.ProxyClient_CannotConnect, $"Unable to connect to gateway at address {Address} on trial {i} (Exception: {ex.Message})"); MarkAsDisconnected(Socket); } } // Failed too many times -- give up MarkAsDead(); } }
// Use this for initialization void Start() { socketManager = GameObject.Find("SocketManager").GetComponent <SocketManager>(); Screen.sleepTimeout = SleepTimeout.NeverSleep; }
public static SocketManager getIns() { if(ins==null) { ins = new SocketManager(); } return ins; }
public static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not) // We do this because almost all of the client/user input/output code does not take culture into account, and assumes en-US formatting. // Without this, many commands that require special characters like , and . will break Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports. System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); // Look for the log4net.config first in the current environment directory, then in the ExecutingAssembly location var exeLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var containerConfigDirectory = "/ace/Config"; var log4netConfig = Path.Combine(exeLocation, "log4net.config"); var log4netConfigExample = Path.Combine(exeLocation, "log4net.config.example"); var log4netConfigContainer = Path.Combine(containerConfigDirectory, "log4net.config"); if (IsRunningInContainer && File.Exists(log4netConfigContainer)) { File.Copy(log4netConfigContainer, log4netConfig, true); } var log4netFileInfo = new FileInfo("log4net.config"); if (!log4netFileInfo.Exists) { log4netFileInfo = new FileInfo(log4netConfig); } if (!log4netFileInfo.Exists) { var exampleFile = new FileInfo(log4netConfigExample); if (!exampleFile.Exists) { Console.WriteLine("log4net Configuration file is missing. Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE."); throw new Exception("missing log4net configuration file"); } else { if (!IsRunningInContainer) { Console.WriteLine("log4net Configuration file is missing, cloning from example file."); File.Copy(log4netConfigExample, log4netConfig); } else { if (!File.Exists(log4netConfigContainer)) { Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container, cloning from docker file."); var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker"); File.Copy(log4netConfigDocker, log4netConfig); File.Copy(log4netConfigDocker, log4netConfigContainer); } else { File.Copy(log4netConfigContainer, log4netConfig); } } } } var logRepository = LogManager.GetRepository(System.Reflection.Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, log4netFileInfo); if (Environment.ProcessorCount < 2) { log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server."); } // Do system specific initializations here try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution MM_BeginPeriod(1); } } catch (Exception ex) { log.Error(ex.ToString()); } log.Info("Starting ACEmulator..."); if (IsRunningInContainer) { log.Info("ACEmulator is running in a container..."); } Console.Title = @$ "ACEmulator - v{ServerBuildInfo.FullVersion}"; var configFile = Path.Combine(exeLocation, "Config.js"); var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js"); if (IsRunningInContainer && File.Exists(configConfigContainer)) { File.Copy(configConfigContainer, configFile, true); } if (!File.Exists(configFile)) { if (!IsRunningInContainer) { DoOutOfBoxSetup(configFile); } else { if (!File.Exists(configConfigContainer)) { DoOutOfBoxSetup(configFile); File.Copy(configFile, configConfigContainer); } else { File.Copy(configConfigContainer, configFile); } } } log.Info("Initializing ConfigManager..."); ConfigManager.Initialize(); if (ConfigManager.Config.Offline.PurgeDeletedCharacters) { log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})..."); ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged); log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions."); } if (ConfigManager.Config.Offline.PurgeOrphanedBiotas) { log.Info($"Purging orphaned biotas..."); ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged); log.Info($"Purged {numberOfBiotasPurged:N0} biotas."); } log.Info("Initializing ServerManager..."); ServerManager.Initialize(); log.Info("Initializing DatManager..."); DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true); log.Info("Initializing DatabaseManager..."); DatabaseManager.Initialize(); log.Info("Starting DatabaseManager..."); DatabaseManager.Start(); log.Info("Starting PropertyManager..."); PropertyManager.Initialize(); log.Info("Initializing GuidManager..."); GuidManager.Initialize(); if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart) { log.Info("Server Performance Monitor auto starting..."); ServerPerformanceMonitor.Start(); } if (ConfigManager.Config.Server.WorldDatabasePrecaching) { log.Info("Precaching Weenies..."); DatabaseManager.World.CacheAllWeeniesInParallel(); log.Info("Precaching Cookbooks..."); DatabaseManager.World.CacheAllCookbooksInParallel(); log.Info("Precaching Events..."); DatabaseManager.World.GetAllEvents(); log.Info("Precaching House Portals..."); DatabaseManager.World.CacheAllHousePortals(); log.Info("Precaching Points Of Interest..."); DatabaseManager.World.CacheAllPointsOfInterest(); log.Info("Precaching Spells..."); DatabaseManager.World.CacheAllSpells(); log.Info("Precaching Treasures - Death..."); DatabaseManager.World.CacheAllTreasuresDeath(); log.Info("Precaching Treasures - Material Base..."); DatabaseManager.World.CacheAllTreasuresMaterialBaseInParallel(); log.Info("Precaching Treasures - Material Groups..."); DatabaseManager.World.CacheAllTreasuresMaterialGroupsInParallel(); log.Info("Precaching Treasures - Material Colors..."); DatabaseManager.World.CacheAllTreasuresMaterialColorInParallel(); log.Info("Precaching Treasures - Wielded..."); DatabaseManager.World.CacheAllTreasuresWieldedInParallel(); } else { log.Info("Precaching World Database Disabled..."); } log.Info("Initializing PlayerManager..."); PlayerManager.Initialize(); log.Info("Initializing HouseManager..."); HouseManager.Initialize(); log.Info("Initializing InboundMessageManager..."); InboundMessageManager.Initialize(); log.Info("Initializing SocketManager..."); SocketManager.Initialize(); log.Info("Initializing WorldManager..."); WorldManager.Initialize(); log.Info("Initializing EventManager..."); EventManager.Initialize(); // Free up memory before the server goes online. This can free up 6 GB+ on larger servers. log.Info("Forcing .net garbage collection..."); for (int i = 0; i < 10; i++) { GC.Collect(); } // This should be last log.Info("Initializing CommandManager..."); CommandManager.Initialize(); if (!PropertyManager.GetBool("world_closed", false).Item) { WorldManager.Open(null); } }
private void SafeCloseSocket(Socket sock) { RecordClosedSocket(sock); SocketManager.CloseSocket(sock); }
/// <summary> /// Process the accept for the socket listener. /// </summary> /// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param> /// <param name="completedSynchronously">Shows whether AcceptAsync completed synchronously, /// if true - the next accept operation woun't be started. Used for avoiding potential stack overflows.</param> private void ProcessAccept(SocketAsyncEventArgs e, bool completedSynchronously) { var ima = e.UserToken as IncomingMessageAcceptor; try { if (ima == null) { Log.Warn(ErrorCode.Messaging_IMA_AcceptCallbackUnexpectedState, "AcceptCallback invoked with an unexpected async state of type {0}", e.UserToken?.GetType().ToString() ?? "null"); return; } if (e.SocketError != SocketError.Success) { RestartAcceptingSocket(); return; } // First check to see if we're shutting down, in which case there's no point in doing anything other // than closing the accepting socket and returning. if (ima.Cts == null || ima.Cts.IsCancellationRequested) { SocketManager.CloseSocket(ima.AcceptingSocket); ima.Log.Info(ErrorCode.Messaging_IMA_ClosingSocket, "Closing accepting socket during shutdown"); return; } Socket sock = e.AcceptSocket; if (sock.Connected) { if (ima.Log.IsEnabled(LogLevel.Debug)) { ima.Log.Debug("Received a connection from {0}", sock.RemoteEndPoint); } // Finally, process the incoming request: // Prep the socket so it will reset on close sock.LingerState = receiveLingerOption; Task.Factory.StartNew(() => { // Add the socket to the open socket collection if (ima.RecordOpenedSocket(sock)) { // Get the socket for the accepted client connection and put it into the // ReadEventArg object user token. var readEventArgs = GetSocketReceiveAsyncEventArgs(sock); StartReceiveAsync(sock, readEventArgs, ima); } else { ima.SafeCloseSocket(sock); } }).Ignore(); } // The next accept will be started in the caller method if (completedSynchronously) { return; } // Start a new Accept StartAccept(e); } catch (Exception ex) { var logger = ima?.Log ?? this.Log; logger.Error(ErrorCode.Messaging_IMA_ExceptionAccepting, "Unexpected exception in IncomingMessageAccepter.AcceptCallback", ex); RestartAcceptingSocket(); } }
partial void OnCloseReaderWriter() { if (ownsSocketManager) socketManager?.Dispose(); socketManager = null; }
void OnDestroy() { // Unsubsribe SocketManager.OnHeartRateChanged -= DoCalculation; SocketManager.Shutdown(); }
private void CloseSocket(Socket socket) { SocketManager.CloseSocket(socket); NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket(); MsgCenter.OnGatewayConnectionClosed(); }
partial void OnCreateReaderWriter(ConfigurationOptions configuration) { this.ownsSocketManager = configuration.SocketManager == null; this.socketManager = configuration.SocketManager ?? new SocketManager(ClientName); }
private void Awake() { instance = this; // SocketManager.ListenDelegate(true, messageHandle, OperationListenInfo); }
private void init() { showSelectImage.Clear(); for (int i = 0; i < contentGo.transform.childCount; i++) { Destroy(contentGo.transform.GetChild(i).gameObject); } itemGo.Clear(); selectItemId = 0; CSGetItems getItems = new CSGetItems(); SocketManager.SendMessageAsyc((int)MiGongOpcode.CSGetItems, CSGetItems.SerializeToBytes(getItems), delegate(int opcode, byte[] data) { Object packetItemObj = Resources.Load("packetItem"); SCGetItems ret = SCGetItems.Deserialize(data); RectTransform contentTrans = contentGo.GetComponent <RectTransform> (); contentTrans.sizeDelta = new Vector2(0, 160 * (ret.Items.Count / 4 + (ret.Items.Count % 4 == 0?0:1))); int step = Screen.width / 8; float scale = Screen.width / 640f; int index = 0; Button btn1 = null; int initSelectItemId = 0; foreach (PBItem item in ret.Items) { if (item.Count > 0) { GameObject go = Instantiate(packetItemObj) as GameObject; itemGo[item.ItemId] = go; PacketItem pi = go.GetComponent <PacketItem>(); pi.itemId = item.ItemId; pi.count = item.Count; int x = index % 4; int y = index / 4; go.transform.localPosition = new Vector3(step * (x * 2 + 1), -160 * y, 0); go.transform.localScale = new Vector3(scale, scale, 1); go.transform.SetParent(contentGo.transform, false); Button btn = go.GetComponent <Button>(); btn.onClick.AddListener(delegate() { Sound.playSound(SoundType.Click); selectItemId = pi.itemId; showInfoByItemType(pi.itemId, btn); }); showSelectImage.Add(btn.GetComponent <Image>()); if (btn1 == null) { btn1 = btn; initSelectItemId = pi.itemId; } index++; } } //调用会触发Button的按钮变色 if (btn1 != null) { showInfoByItemType(initSelectItemId, btn1); btn1.Select(); selectItemId = initSelectItemId; } else { text.text = ""; useButton.gameObject.SetActive(false); } }); }
public IncomingPacket Parse(SocketManager manager, BufferSegment data, TransportEventTypes transportEvent = TransportEventTypes.Unknown) { using (var stream = new System.IO.MemoryStream(data.Data, data.Offset, data.Count)) { var buff = BufferPool.Get(MsgPackReader.DEFAULT_BUFFER_SIZE, true); try { var context = new SerializationContext { Options = SerializationOptions.SuppressTypeInformation/*, * ExtensionTypeHandler = CustomMessagePackExtensionTypeHandler.Instance*/ }; IJsonReader reader = new MsgPackReader(stream, context, Endianness.BigEndian, buff); reader.ReadObjectBegin(); int type = -1, id = -1; string nsp = null; bool hasData = false, readData = false; IncomingPacket packet = IncomingPacket.Empty; READ: while (reader.Token != JsonToken.EndOfObject) { string key = reader.ReadMember(); switch (key) { case "type": type = reader.ReadByte(); break; case "nsp": nsp = reader.ReadString(); break; case "id": id = reader.ReadInt32(); break; case "data": if (!hasData) { hasData = true; SkipData(reader, (SocketIOEventTypes)type); } else { readData = true; packet = new IncomingPacket(transportEvent != TransportEventTypes.Unknown ? transportEvent : TransportEventTypes.Message, (SocketIOEventTypes)type, nsp, id); (string eventName, object[] args) = ReadData(manager, packet, reader); packet.EventName = eventName; if (args != null) { if (args.Length == 1) { packet.DecodedArg = args[0]; } else { packet.DecodedArgs = args; } } } break; } } // type, nsp, id and data can come in any order. To read data strongly typed we need to know all the additional fields before processing the data field. // In order to do it, when we first encounter the data field we skip it than we do a reset and an additional turn but reading the data too now. if (hasData && !readData) { reader.Reset(); stream.Position = 0; reader.ReadObjectBegin(); goto READ; } reader.ReadObjectEnd(); return(packet.Equals(IncomingPacket.Empty) ? new IncomingPacket(transportEvent != TransportEventTypes.Unknown ? transportEvent : TransportEventTypes.Message, (SocketIOEventTypes)type, nsp, id) : packet); } finally { BufferPool.Release(buff); } } }
partial void OnCloseReaderWriter() { SocketManager = null; }
public IncomingPacket MergeAttachements(SocketManager manager, IncomingPacket packet) { return(packet); }
partial void OnCreateReaderWriter(ConfigurationOptions configuration) { SocketManager = configuration.SocketManager ?? SocketManager.Shared; }
static void Main() { //Set Culture CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; if (!ConfigMgr.Load("BNetServer.conf")) { ExitNow(); } // Initialize the database if (!StartDB()) { ExitNow(); } FixLegacyAuthHashes(); string bindIp = ConfigMgr.GetDefaultValue("BindIP", "0.0.0.0"); var restSocketServer = new SocketManager <RestSession>(); int restPort = ConfigMgr.GetDefaultValue("LoginREST.Port", 8081); if (restPort < 0 || restPort > 0xFFFF) { Log.outError(LogFilter.Network, "Specified login service port ({restPort}) out of allowed range (1-65535), defaulting to 8081"); restPort = 8081; } if (!restSocketServer.StartNetwork(bindIp, restPort)) { Log.outError(LogFilter.Server, "Failed to initialize Rest Socket Server"); ExitNow(); } // Get the list of realms for the server Global.RealmMgr.Initialize(ConfigMgr.GetDefaultValue("RealmsStateUpdateDelay", 10)); Global.LoginServiceMgr.Initialize(); var sessionSocketServer = new SocketManager <Session>(); // Start the listening port (acceptor) for auth connections int bnPort = ConfigMgr.GetDefaultValue("BattlenetPort", 1119); if (bnPort < 0 || bnPort > 0xFFFF) { Log.outError(LogFilter.Server, $"Specified battle.net port ({bnPort}) out of allowed range (1-65535)"); ExitNow(); } if (!sessionSocketServer.StartNetwork(bindIp, bnPort)) { Log.outError(LogFilter.Network, "Failed to start BnetServer Network"); ExitNow(); } uint _banExpiryCheckInterval = ConfigMgr.GetDefaultValue("BanExpiryCheckInterval", 60u); _banExpiryCheckTimer = new Timer(_banExpiryCheckInterval); _banExpiryCheckTimer.Elapsed += BanExpiryCheckTimer_Elapsed; _banExpiryCheckTimer.Start(); }
public void initBoard() { firstScreenMsg = Instantiate( Resources.Load<GameObject>("prefabs/message_waiting"), Vector3.zero, Quaternion.identity ) as GameObject; socketManager = GameObject.Find("SocketManager").GetComponent<SocketManager>(); UICanvas = GameObject.Find("UICanvas"); cardGroup = GameObject.Find("CardGroup"); UICanvas.SetActive(false); cardGroup.SetActive(false); }
void Start() { m_pRelayConnector = null; m_pSocketManager = null; m_pProcessUnit = null; m_pProcessUnitBank = null; m_PUUID = 0; m_RPCID = 0; }
public void SetSocketManager( SocketManager pManager ) { m_pSocketManager = pManager; }
private static void AcceptCallback(IAsyncResult result) { var ima = result.AsyncState as IncomingMessageAcceptor; try { if (ima == null) { var logger = LogManager.GetLogger("IncomingMessageAcceptor", LoggerType.Runtime); if (result.AsyncState == null) { logger.Warn(ErrorCode.Messaging_IMA_AcceptCallbackNullState, "AcceptCallback invoked with a null unexpected async state"); } else { logger.Warn(ErrorCode.Messaging_IMA_AcceptCallbackUnexpectedState, "AcceptCallback invoked with an unexpected async state of type {0}", result.AsyncState.GetType()); } return; } // First check to see if we're shutting down, in which case there's no point in doing anything other // than closing the accepting socket and returning. if (ima.Cts.IsCancellationRequested) { SocketManager.CloseSocket(ima.AcceptingSocket); ima.Log.Info(ErrorCode.Messaging_IMA_ClosingSocket, "Closing accepting socket during shutdown"); return; } // Then, start a new Accept try { ima.AcceptingSocket.BeginAccept(AcceptCallback, ima); } catch (Exception ex) { ima.Log.Warn(ErrorCode.MessagingBeginAcceptSocketException, "Exception on accepting socket during BeginAccept", ex); // Open a new one ima.RestartAcceptingSocket(); } Socket sock; // Complete this accept try { sock = ima.AcceptingSocket.EndAccept(result); } catch (ObjectDisposedException) { // Socket was closed, but we're not shutting down; we need to open a new socket and start over... // Close the old socket and open a new one ima.Log.Warn(ErrorCode.MessagingAcceptingSocketClosed, "Accepting socket was closed when not shutting down"); ima.RestartAcceptingSocket(); return; } catch (Exception ex) { // There was a network error. We need to get a new accepting socket and re-issue an accept before we continue. // Close the old socket and open a new one ima.Log.Warn(ErrorCode.MessagingEndAcceptSocketException, "Exception on accepting socket during EndAccept", ex); ima.RestartAcceptingSocket(); return; } if (ima.Log.IsVerbose3) { ima.Log.Verbose3("Received a connection from {0}", sock.RemoteEndPoint); } // Finally, process the incoming request: // Prep the socket so it will reset on close sock.LingerState = new LingerOption(true, 0); // Add the socket to the open socket collection if (ima.RecordOpenedSocket(sock)) { // And set up the asynch receive var rcc = new ReceiveCallbackContext(sock, ima); try { rcc.BeginReceive(ReceiveCallback); } catch (Exception exception) { var socketException = exception as SocketException; ima.Log.Warn(ErrorCode.Messaging_IMA_NewBeginReceiveException, String.Format("Exception on new socket during BeginReceive with RemoteEndPoint {0}: {1}", socketException != null ? socketException.SocketErrorCode.ToString() : "", rcc.RemoteEndPoint), exception); ima.SafeCloseSocket(sock); } } else { ima.SafeCloseSocket(sock); } } catch (Exception ex) { var logger = ima != null ? ima.Log : LogManager.GetLogger("IncomingMessageAcceptor", LoggerType.Runtime); logger.Error(ErrorCode.Messaging_IMA_ExceptionAccepting, "Unexpected exception in IncomingMessageAccepter.AcceptCallback", ex); } }
public static void Main(string[] args) { AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports. System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); var logRepository = LogManager.GetRepository(System.Reflection.Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); // Do system specific initializations here try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution MM_BeginPeriod(1); } } catch (Exception ex) { log.Error(ex.ToString()); } log.Info("Starting ACEmulator..."); Console.Title = @"ACEmulator"; log.Info("Initializing ConfigManager..."); ConfigManager.Initialize(); log.Info("Initializing ServerManager..."); ServerManager.Initialize(); log.Info("Initializing DatManager..."); DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory); log.Info("Initializing DatabaseManager..."); DatabaseManager.Initialize(); log.Info("Starting DatabaseManager..."); DatabaseManager.Start(); log.Info("Starting PropertyManager..."); PropertyManager.Initialize(); log.Info("Initializing GuidManager..."); GuidManager.Initialize(); log.Info("Initializing InboundMessageManager..."); InboundMessageManager.Initialize(); log.Info("Initializing SocketManager..."); SocketManager.Initialize(); log.Info("Initializing WorldManager..."); WorldManager.Initialize(); log.Info("Initializing EventManager..."); EventManager.Initialize(); // This should be last log.Info("Initializing CommandManager..."); CommandManager.Initialize(); }
public void Send() { SocketManager.Instance().SendMessage(this); }
private bool Send(Message msg, Socket sock) { if (Cts.IsCancellationRequested) { return(false); } if (sock == null) { return(false); } // Send the message List <ArraySegment <byte> > data; int headerLength; try { int bodyLength; data = msg.Serialize(this.serializationManager, out headerLength, out bodyLength); if (headerLength + bodyLength > this.serializationManager.LargeObjectSizeThreshold) { Log.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}", headerLength + bodyLength + Message.LENGTH_HEADER_SIZE, headerLength, bodyLength, data.Count, this.ToString()); if (Log.IsVerbose3) { Log.Verbose3("Sending large message {0}", msg.ToLongString()); } } } catch (Exception exc) { this.OnMessageSerializationFailure(msg, exc); return(true); } int length = data.Sum(x => x.Count); int bytesSent = 0; bool exceptionSending = false; bool countMismatchSending = false; string sendErrorStr; try { bytesSent = sock.Send(data); if (bytesSent != length) { // The complete message wasn't sent, even though no error was reported; treat this as an error countMismatchSending = true; sendErrorStr = String.Format("Byte count mismatch on send: sent {0}, expected {1}", bytesSent, length); Log.Warn(ErrorCode.GatewayByteCountMismatch, sendErrorStr); } } catch (Exception exc) { exceptionSending = true; string remoteEndpoint = ""; if (!(exc is ObjectDisposedException)) { try { remoteEndpoint = sock.RemoteEndPoint.ToString(); } catch (Exception) {} } sendErrorStr = String.Format("Exception sending to client at {0}: {1}", remoteEndpoint, exc); Log.Warn(ErrorCode.GatewayExceptionSendingToClient, sendErrorStr, exc); } MessagingStatisticsGroup.OnMessageSend(msg.TargetSilo, msg.Direction, bytesSent, headerLength, SocketDirection.GatewayToClient); bool sendError = exceptionSending || countMismatchSending; if (sendError) { gateway.RecordClosedSocket(sock); SocketManager.CloseSocket(sock); } gatewaySends.Increment(); msg.ReleaseBodyAndHeaderBuffers(); return(!sendError); }