Exemple #1
0
 public override void Recycle()
 {
     base.Recycle();
     Status         = ConnectionStatus.None;
     _socketService = null;
     _serverSocket  = null;
 }
    private void StartServer()
    {
        _clients = new List <IPeer>();

        if (useWs)
        {
            _server = new ServerSocketWs();
        }
        else
        {
            _server = new ServerSocketUnet();
        }

        _server.Connected    += ClientConnected;
        _server.Disconnected += ClientDisconnected;

        // Start listening
        Debug.Log("Server: listening on port " + port);
        _server.Listen(port);

        if (sendMessages)
        {
            StartCoroutine(SendMessages(1f));
        }
    }
Exemple #3
0
        protected virtual void Awake()
        {
            Application.targetFrameRate = targetFrameRate;

            logger          = Mst.Create.Logger(GetType().Name);
            logger.LogLevel = logLevel;

            connectedPeers     = new Dictionary <int, IPeer>();
            modules            = new Dictionary <Type, IBaseServerModule>();
            initializedModules = new HashSet <Type>();
            handlers           = new Dictionary <short, IPacketHandler>();
            peersByGuidLookup  = new Dictionary <Guid, IPeer>();

            // Create the server
            socket                     = Mst.Create.ServerSocket();
            socket.UseSsl              = useSsl || Mst.Args.UseSsl;
            socket.CertificatePath     = Mst.Args.ExtractValue(Mst.Args.Names.CertificatePath, certificatePath);
            socket.CertificatePassword = Mst.Args.ExtractValue(Mst.Args.Names.CertificatePassword, certificatePassword);

            socket.OnPeerConnectedEvent    += OnConnectedEventHandle;
            socket.OnPeerDisconnectedEvent += OnDisconnectedEventHandler;

            // AesKey handler
            SetHandler((short)MstMessageCodes.AesKeyRequest, GetAesKeyRequestHandler);
            SetHandler((short)MstMessageCodes.PermissionLevelRequest, PermissionLevelRequestHandler);
            SetHandler((short)MstMessageCodes.PeerGuidRequest, GetPeerGuidRequestHandler);
        }
Exemple #4
0
        public Server(string id, RawMessageManager rawMessageManager, ModuleManager moduleManager,
                      CacheManager cacheManager, ControllerComponentManager controllerComponentManager)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException(nameof(id));
            }

            ID = id;
            LuaHelper.RegisterType <Server>();

            _moduleManager = moduleManager ?? throw new ArgumentNullException(nameof(moduleManager));
            _cacheManager  = cacheManager ?? throw new ArgumentNullException(nameof(cacheManager));
            _controllerComponentManager = controllerComponentManager ?? throw new ArgumentNullException(nameof(controllerComponentManager));
            _rawMessageManager          = rawMessageManager ?? throw new ArgumentNullException(nameof(rawMessageManager));

            _events = new Dictionary <string, Action <IUser, object> >();

            _serverSocket               = new ServerSocket(id);
            _serverSocket.Accepted     += AcceptConnected;
            _serverSocket.Connected    += PeerConnected;
            _serverSocket.Disconnected += PeerDisconnected;

            RpcRegister.RegisterMethod(this);

            RpcMethodIds   = new List <string>();
            RpcPacketTypes = new List <string>();
        }
Exemple #5
0
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public void Start(IPEndPoint endpoint)
        {
            if (!_run)
            {
                _run = true;
                try
                {
                    _udpServer = SocketFactory.CreateServerSocket(SocketOptionBuilder.Instance.SetSocket(SAEASocketType.Udp)
                                                                  .SetIPEndPoint(endpoint)
                                                                  .UseIocp <BaseContext>()
                                                                  .SetReadBufferSize(SocketOption.UDPMaxLength)
                                                                  .SetWriteBufferSize(SocketOption.UDPMaxLength)
                                                                  .SetTimeOut(UDP_TIMEOUT)
                                                                  .SetFreeTime(30 * 1000)
                                                                  .Build());

                    _udpServer.OnError   += _udpServer_OnError;
                    _udpServer.OnReceive += _udpServer_OnReceive;

                    _udpServer.Start();

                    OnEvent(OnListening, EventArgs.Empty);
                }
                catch (SocketException e)
                {
                    OnError(e);
                    return;
                }
            }
        }
Exemple #6
0
        protected virtual void Awake()
        {
            if (string.IsNullOrEmpty(MstApplicationConfig.Instance.ApplicationKey))
            {
                throw new Exception("ApplicationKey is not defined");
            }

            Application.targetFrameRate = Mst.Args.AsInt(Mst.Args.Names.TargetFrameRate, targetFrameRate);

            logger          = Mst.Create.Logger(GetType().Name);
            logger.LogLevel = logLevel;

            connectedPeers     = new Dictionary <int, IPeer>();
            modules            = new Dictionary <Type, IBaseServerModule>();
            initializedModules = new HashSet <Type>();
            handlers           = new Dictionary <short, IPacketHandler>();
            peersByGuidLookup  = new Dictionary <Guid, IPeer>();

            // Create the server
            socket = Mst.Create.ServerSocket();

            // Setup secure connection
            socket.UseSecure           = MstApplicationConfig.Instance.UseSecure;
            socket.CertificatePath     = MstApplicationConfig.Instance.CertificatePath;
            socket.CertificatePassword = MstApplicationConfig.Instance.CertificatePassword;
            socket.ApplicationKey      = MstApplicationConfig.Instance.ApplicationKey;

            socket.OnPeerConnectedEvent    += OnPeerConnectedEventHandle;
            socket.OnPeerDisconnectedEvent += OnPeerDisconnectedEventHandler;

            // AesKey handler
            RegisterMessageHandler((short)MstMessageCodes.AesKeyRequest, GetAesKeyRequestHandler);
            RegisterMessageHandler((short)MstMessageCodes.PermissionLevelRequest, PermissionLevelRequestHandler);
            RegisterMessageHandler((short)MstMessageCodes.PeerGuidRequest, GetPeerGuidRequestHandler);
        }
Exemple #7
0
        public MessageServer(int port = 39654, int bufferSize = 102400, int count = 1000, int timeOut = 60 * 1000)
        {
            var option = SocketOptionBuilder.Instance
                         .SetPort(port)
                         .UseIocp <MessageContext>()
                         .SetReadBufferSize(bufferSize)
                         .SetWriteBufferSize(bufferSize)
                         .SetCount(count)
                         .SetTimeOut(timeOut)
                         .Build();

            _server = SocketFactory.CreateServerSocket(option);

            _server.OnAccepted += _server_OnAccepted;

            _server.OnReceive += _server_OnReceive;

            _server.OnError += _server_OnError;

            _server.OnDisconnected += _server_OnDisconnected;

            _classificationBatcher = ClassificationBatcher.GetInstance(10000, 10);

            _classificationBatcher.OnBatched += _classificationBatcher_OnBatched;
        }
Exemple #8
0
        public MqttTcpServerListener(
            AddressFamily addressFamily,
            MqttServerTcpEndpointBaseOptions options,
            X509Certificate2 tlsCertificate,
            CancellationToken cancellationToken,
            IMqttNetChildLogger logger)
        {
            _cancellationToken = cancellationToken;
            _logger            = logger;
            _addressFamily     = addressFamily;

            var sb = new SocketOptionBuilder().SetSocket(Sockets.Model.SAEASocketType.Tcp).UseStream();

            if (options is MqttServerTlsTcpEndpointOptions tlsOptions)
            {
                sb = sb.WithSsl(tlsCertificate, tlsOptions.SslProtocol);
            }

            sb = sb.SetPort(options.Port);

            if (_addressFamily == AddressFamily.InterNetworkV6)
            {
                sb = sb.UseIPv6();
            }

            socketOption = sb.Build();

            serverSokcet = SocketFactory.CreateServerSocket(socketOption, cancellationToken);

            serverSokcet.OnAccepted += ServerSokcet_OnAccepted;
        }
Exemple #9
0
        public void Start(IServerSocket socket)
        {
            _socket = socket;
            var thread = new Thread(new ParameterizedThreadStart(ping));

            thread.Start(_socket);
        }
Exemple #10
0
 public void Start(int port)
 {
     _server = new IServerSocket(10, 1024 * 4);
     _server.Init();
     _server.Start("0.0.0.0", port);
     _server.OnClientConnect    += _server_OnClientConnect;
     _server.OnClientRead       += _server_OnClientRead;
     _server.OnClientDisconnect += _server_OnClientDisconnect;
 }
Exemple #11
0
        public void Listen(int port)
        {
            if (ServerSocket != null)
            {
                throw new Exception("Socket already running!");
            }

            ServerSocket = ServerSocketBuilder.Build();
            ServerSocket.listen(port);
        }
Exemple #12
0
        public SpeedDateServer(IServerSocket serverSocket, ILogger logger)
        {
            _connectedPeers = new Dictionary <long, IPeer>();
            _handlers       = new Dictionary <short, IPacketHandler>();

            // Create the server
            _socket = serverSocket;
            _logger = logger;

            _socket.Connected    += Connected;
            _socket.Disconnected += Disconnected;
        }
Exemple #13
0
        public void LogSocket(IServerSocket socket, string message)
        {
            lock (_lock)
            {
                var data = new XElement(socket.Type,
                                        new object[] {
                    new XAttribute("Time", DateTime.Now.ToString())
                    , new XElement(socket.Name, new [] { new XElement("Message", message) })
                });

                WriteLog(data);
            }
        }
 public void StartMsgServer()
 {
     try
     {
         MsgServer = new IServerSocket(20, Int16.MaxValue);
         MsgServer.Init();
         MsgServer.Start(M2Share.g_Config.sMsgSrvAddr, M2Share.g_Config.nMsgSrvPort);
     }
     catch
     {
         M2Share.MainOutMessage("{Òì³£} TFrmSrvMsg::StartMsgServer");
     }
 }
Exemple #15
0
        /// <summary>
        /// TCPServer
        /// </summary>
        /// <param name="endpoint"></param>
        public TCPServer(IPEndPoint endpoint)
        {
            //tcpserver
            _serverSokcet = SocketFactory.CreateServerSocket(SocketOptionBuilder.Instance
                                                             .SetSocket(Model.SAEASocketType.Tcp)
                                                             .SetIPEndPoint(endpoint)
                                                             .UseIocp <Coder>()
                                                             .Build());

            _serverSokcet.OnAccepted     += ServerSokcet_OnAccepted;
            _serverSokcet.OnDisconnected += ServerSokcet_OnDisconnected;
            _serverSokcet.OnError        += ServerSokcet_OnError;
            _serverSokcet.OnReceive      += ServerSokcet_OnReceive;
        }
Exemple #16
0
        public JServer()
        {
            //tcpserver
            _serverSokcet = SocketFactory.CreateServerSocket(SocketOptionBuilder.Instance
                                                             .SetSocket(Model.SAEASocketType.Tcp)
                                                             .SetPort(39808)
                                                             .UseIocp <JContext>()
                                                             .Build());

            _serverSokcet.OnAccepted     += ServerSokcet_OnAccepted;
            _serverSokcet.OnDisconnected += ServerSokcet_OnDisconnected;
            _serverSokcet.OnError        += ServerSokcet_OnError;
            _serverSokcet.OnReceive      += ServerSokcet_OnReceive;
        }
        public bool Start(bool treatErrorsAsWarning, CancellationToken cancellationToken)
        {
            try
            {
                var builder = SocketOptionBuilder.Instance;

                var boundIp = _options.BoundInterNetworkAddress;

                if (_addressFamily == AddressFamily.InterNetworkV6)
                {
                    builder = builder.UseIPv6();

                    boundIp = _options.BoundInterNetworkV6Address;
                }

                _localEndPoint = new IPEndPoint(boundIp, _options.Port);

                _logger.Info($"Starting TCP listener for {_localEndPoint} TLS={_tlsCertificate != null}.");

                builder = builder.ReusePort(_options.ReuseAddress);

                if (!_options.NoDelay)
                {
                    builder = builder.SetDelay();
                }

                if (_tlsCertificate != null)
                {
                    builder = builder.WithSsl(_tlsCertificate, System.Security.Authentication.SslProtocols.Tls12);
                }

                _serverSokcet = SocketFactory.CreateServerSocket(builder.UseStream().SetIPEndPoint(_localEndPoint).Build());

                _serverSokcet.OnAccepted += _serverSokcet_OnAccepted;

                _serverSokcet.Start(_options.ConnectionBacklog);

                return(true);
            }
            catch (Exception exception)
            {
                if (!treatErrorsAsWarning)
                {
                    throw;
                }

                _logger.Warning(exception, "Error while creating listener socket for local end point '{0}'.", _localEndPoint);
                return(false);
            }
        }
Exemple #18
0
        public AudioServer(IPEndPoint endPoint)
        {
            _cache = new ConcurrentDictionary <string, IUserToken>();

            _udpServer = SocketFactory.CreateServerSocket(SocketOptionBuilder.Instance.SetSocket(SAEASocketType.Udp)
                                                          .SetIPEndPoint(endPoint)
                                                          .UseIocp <BaseContext>()
                                                          .SetReadBufferSize(SocketOption.UDPMaxLength)
                                                          .SetWriteBufferSize(SocketOption.UDPMaxLength)
                                                          .SetTimeOut(5000)
                                                          .Build());
            _udpServer.OnAccepted     += _udpServer_OnAccepted;
            _udpServer.OnDisconnected += _udpServer_OnDisconnected;
            _udpServer.OnReceive      += _udpServer_OnReceive;
        }
Exemple #19
0
        /// <summary>
        /// UDPServer
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="timeOut"></param>
        public UDPServer(IPEndPoint endPoint, int timeOut = 5000)
        {
            _udpServer = SocketFactory.CreateServerSocket(SocketOptionBuilder.Instance.SetSocket(SAEASocketType.Udp)
                                                          .SetIPEndPoint(endPoint)
                                                          .UseIocp <Coder>()
                                                          .SetReadBufferSize(SocketOption.UDPMaxLength)
                                                          .SetWriteBufferSize(SocketOption.UDPMaxLength)
                                                          .SetTimeOut(timeOut)
                                                          .Build());

            _udpServer.OnAccepted     += UdpServer_OnAccepted;
            _udpServer.OnDisconnected += UdpServer_OnDisconnected;
            _udpServer.OnError        += UdpServer_OnError;
            _udpServer.OnReceive      += UdpServer_OnReceive;
        }
Exemple #20
0
 public void FormCreate(System.Object Sender, System.EventArgs _e1)
 {
     DBShare.Initialization();
     DBShare.MainOutMessage("正在启动数据库服务器...");
     FrmIDSoc = new TFrmIDSoc(this);
     FrmIDSoc.Show();
     FrmIDSoc.Hide();
     ModuleGrid.AllowUserToAddRows = false;
     ModuleGrid.RowHeadersVisible  = false;
     ModuleGrid.ReadOnly           = true;
     ModuleGrid.Columns.Add("MKMC", "模块名称");
     ModuleGrid.Columns.Add("LJDZ", "连接地址");
     ModuleGrid.Columns.Add("SJTX", "数据通讯");
     ModuleGrid.Columns[0].Width    = 80;
     ModuleGrid.Columns[1].Width    = 468 - 80 * 2;
     ModuleGrid.Columns[2].Width    = 80;
     ModuleGrid.SelectionMode       = DataGridViewSelectionMode.FullRowSelect;
     ModuleGrid.MultiSelect         = false;
     ModuleGrid.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
     ModuleGrid.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
     ModuleGrid.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;
     ModuleGrid.RowTemplate.Height  = 18;
     ModuleGrid.Rows.Add(5);
     //M2套接字
     ServerSocket = new IServerSocket(1000, Int16.MaxValue);
     ServerSocket.OnClientConnect     += ServerSocket_OnClientConnect;
     ServerSocket.OnClientDisconnect  += ServerSocket_OnClientDisconnect;
     ServerSocket.OnClientError       += ServerSocket_OnClientError;
     ServerSocket.OnClientRead        += ServerSocket_OnClientRead;
     ServerSocket.OnDataSendCompleted += ServerSocket_OnDataSendCompleted;
     //选择服务器套接字
     SelectSocket = new IServerSocket(1000, Int16.MaxValue);
     SelectSocket.OnClientConnect     += SelectSocket_OnClientConnect;
     SelectSocket.OnClientDisconnect  += SelectSocket_OnClientDisconnect;
     SelectSocket.OnClientError       += SelectSocket_OnClientError;
     SelectSocket.OnClientRead        += SelectSocket_OnClientRead;
     SelectSocket.OnDataSendCompleted += SelectSocket_OnDataSendCompleted;
     ServerSocket.Init();
     SelectSocket.Init();
     CheckBoxShowMainLogMsg.Checked = DBShare.g_boShowLogMsg;
     //Units.Main.RankingThread = new TRankingThread(true);
     //Units.Main.RankingThread.Resume();
     DBShare.SendGameCenterMsg(Common.SG_STARTNOW, "正在启动数据库服务器...");
     TimerMain  = new System.Threading.Timer(TimerMainTimer, null, 0, 1);
     TimerStart = new System.Threading.Timer(TimerStartTimer, null, -1, -1);
     TimerClose = new System.Threading.Timer(TimerCloseTimer, null, -1, -1);
     TimerStart.Change(0, 1000);
 }
Exemple #21
0
 public Server(string IP, int port, string user, string password, string url, string database)
 {
     ServerCallDatabase            = new ServerCallDatabase();
     ServerSocket                  = new ServerSocket();
     ServerSocket.OnClientOffline += ClientOffline;
     ServerSocket.OnException     += OnException;
     runningData = new RunningData(IP, port, user, password, url, database);
     //Clients_remoteEndPoint = new Dictionary<string, UserInfo>();
     //Clients_id = new Dictionary<string, string>();
     //this.ip = IP;
     //this.port = port;
     //this.user = user;
     //this.password = password;
     //this.url = url;
     //this.database = database;
 }
Exemple #22
0
        public UDPServer()
        {
            _udpServer = SocketFactory.CreateServerSocket(SocketOptionBuilder.Instance.SetSocket(SAEASocketType.Udp)
                                                          .SetIP("127.0.0.1")
                                                          .SetPort(39656)
                                                          .UseIocp <BaseContext>()
                                                          .SetReadBufferSize(SocketOption.UDPMaxLength)
                                                          .SetWriteBufferSize(SocketOption.UDPMaxLength)
                                                          .SetTimeOut(5000)
                                                          .Build());

            _udpServer.OnAccepted     += UdpServer_OnAccepted;
            _udpServer.OnDisconnected += UdpServer_OnDisconnected;
            _udpServer.OnError        += UdpServer_OnError;
            _udpServer.OnReceive      += UdpServer_OnReceive;
        }
Exemple #23
0
        public HttpSocketDebug(int port, int bufferSize = 1024 * 10, int count = 10000, int timeOut = 120 * 1000)
        {
            var optionBuilder = new SocketOptionBuilder()
                                .SetSocket(Sockets.Model.SAEASocketType.Tcp)
                                .UseIocp <HContext>()
                                .SetPort(port)
                                .SetCount(count)
                                .SetReadBufferSize(bufferSize)
                                .SetTimeOut(timeOut)
                                .ReusePort(false);

            _option = optionBuilder.Build();

            _serverSokcet            = SocketFactory.CreateServerSocket(_option);
            _serverSokcet.OnReceive += _serverSokcet_OnReceive;
        }
Exemple #24
0
        public RServer(int port = 39654, int bufferSize = 100 * 1024, int count = 10000)
        {
            var option = SocketOptionBuilder.Instance
                         .SetSocket()
                         .UseIocp <RUnpacker>()
                         .SetPort(port)
                         .SetReadBufferSize(bufferSize)
                         .SetWriteBufferSize(bufferSize)
                         .SetCount(count)
                         .Build();

            _server = SocketFactory.CreateServerSocket(option);

            _server.OnError += _server_OnError;

            _server.OnReceive += _server_OnReceive;
        }
Exemple #25
0
        /// <summary>
        /// websocket server
        /// </summary>
        /// <param name="port"></param>
        /// <param name="bufferSize"></param>
        /// <param name="count"></param>
        public WSServerImpl(int port = 16666, int bufferSize = 1024, int count = 60000)
        {
            var option = SocketOptionBuilder.Instance
                         .SetSocket()
                         .UseIocp <WSContext>()
                         .SetPort(port)
                         .SetReadBufferSize(bufferSize)
                         .SetWriteBufferSize(bufferSize)
                         .SetCount(count)
                         .Build();

            _server = SocketFactory.CreateServerSocket(option);

            _server.OnReceive += _server_OnReceive;

            _server.OnDisconnected += _server_OnDisconnected;
        }
Exemple #26
0
        /// <summary>
        /// 语音传输服务器
        /// </summary>
        /// <param name="endPoint"></param>
        public TransferServer(IPEndPoint endPoint)
        {
            _cache = new ConcurrentDictionary <string, IUserToken>();

            _invitedMapping = new ConcurrentDictionary <string, string>();

            _udpServer = SocketFactory.CreateServerSocket(SocketOptionBuilder.Instance.SetSocket(SAEASocketType.Udp)
                                                          .SetIPEndPoint(endPoint)
                                                          .UseIocp()
                                                          .SetReadBufferSize(SocketOption.UDPMaxLength)
                                                          .SetWriteBufferSize(SocketOption.UDPMaxLength)
                                                          .SetTimeOut(60 * 1000)
                                                          .Build());
            _udpServer.OnAccepted     += _udpServer_OnAccepted;
            _udpServer.OnDisconnected += _udpServer_OnDisconnected;
            _udpServer.OnReceive      += _udpServer_OnReceive;

            _storage = StorageFactory.Create <T>();
        }
        protected virtual void Awake()
        {
            ConnectedPeers      = new Dictionary <int, IPeer>();
            _modules            = new Dictionary <Type, IServerModule>();
            _initializedModules = new HashSet <Type>();
            Handlers            = new Dictionary <short, IPacketHandler>();
            PeersByGuidLookup   = new Dictionary <Guid, IPeer>();

            // Create the server
            Socket = Msf.Create.ServerSocket();

            Socket.Connected    += Connected;
            Socket.Disconnected += Disconnected;

            // AesKey handler
            SetHandler((short)MsfOpCodes.AesKeyRequest, HandleAesKeyRequest);
            SetHandler((short)MsfOpCodes.RequestPermissionLevel, HandlePermissionLevelRequest);
            SetHandler((short)MsfOpCodes.PeerGuidRequest, HandleGetPeerGuidRequest);
        }
Exemple #28
0
        public WSSServerImpl(SslProtocols sslProtocols, string pfxPath, string pwd = "", int port = 16666, int bufferSize = 1024)
        {
            _bufferSize = bufferSize;

            var builder = SocketOptionBuilder.Instance
                          .UseStream()
                          .SetPort(port)
                          .WithSsl(sslProtocols, pfxPath, pwd);

            var options = builder.Build();

            serverSokcet = SocketFactory.CreateServerSocket(options);

            serverSokcet.OnAccepted += ServerSokcet_OnAccepted;

            serverSokcet.OnDisconnected += ServerSokcet_OnDisconnected;

            _concurrentDictionary = new ConcurrentDictionary <string, WSCoder>();
        }
Exemple #29
0
        public FTPDataSocketManager(string userName, ushort port, int bufferSize = 10240)
        {
            _autoResetEvent = new AutoResetEvent(false);

            var option = SocketOptionBuilder.Instance
                         .SetSocket()
                         .UseIocp()
                         .SetPort(port)
                         .SetReadBufferSize(bufferSize)
                         .SetWriteBufferSize(bufferSize)
                         .Build();
            var dataSocket = SocketFactory.CreateServerSocket(option);

            dataSocket.OnAccepted     += DataSocket_OnAccepted;
            dataSocket.OnDisconnected += DataSocket_OnDisconnected;
            dataSocket.OnError        += _serverSocket_OnError;
            dataSocket.OnReceive      += DataSocket_OnReceive;
            _dataSocket = dataSocket;
            _userName   = userName;
            _dataSocket.Start();
        }
Exemple #30
0
        public void SetStatus(ConnectionStatus status, SocketService socketService, IServerSocket serverSocket)
        {
            if (socketService == null)
            {
                Logger.Error($"{nameof(socketService)} 为 null");
                return;
            }

            if (status != ConnectionStatus.Connected)
            {
                Logger.Debug("Disconnected!");
            }

            Status = status;
            if (status == ConnectionStatus.Connected)
            {
                _socketService = socketService;
            }

            _serverSocket = serverSocket ?? throw new ArgumentNullException(nameof(serverSocket));
        }
 public CavernaPlayer(int food, IServerSocket serverSocket)
 {
     _serverSocket = serverSocket;
     tilesManager = new CavernaPlayerTilesManager(this);
     animalManager = new AnimalManager();
     _playerResources = new PlayerResources();
     _newRoundBonuses = new List<List<string>>();
     //these will trigger a ui update, in case you started a new game
     Wood = 0;
     Ore = 0;
     Stone = 0;
     Veg = 0;
     Grain = 0;
     Food = food;
     Rubies = 0;
     Gold = 0;
     BeggingCards = 0;
     _dwarves.Add(new Dwarf(false, _dwarves.Count+1));
     _dwarves.Add(new Dwarf(false, _dwarves.Count+1));
     CalculatePlayerScore();
 }
        public void SetTileAt(IServerSocket serverSocket, Vector2 position, bool isForest, bool isExpedition, out int foodGain, out int pigsGain, out int rubyGain)
        {
            foodGain = 0;
            pigsGain = 0;
            rubyGain = 0;

            if (TilesToPlace.First() == TileTypes.SmallFence)
            {
                if (isExpedition)
                {
                    //already paid for
                }
                else
                {
                    int woodCost = 2;
                    if (HasTile(BuildingTypes.Carpenter))
                    {
                        woodCost --;
                    }
                    _player.Wood -= woodCost;
                }
            }
            if (TilesToPlace.First() == TileTypes.BigFence1)
            {
                if (isExpedition)
                {
                    //already paid for
                }
                else
                {
                    int woodCost = 4;
                    if (HasTile(BuildingTypes.Carpenter))
                    {
                        woodCost--;
                    }
                    _player.Wood -= woodCost;
                }
            }
            if (TilesToPlace.First() == TileTypes.Stable)
            {
                //pay for the stable
                if (!HasTile(BuildingTypes.StoneCarver) && !isExpedition)
                {
                    _player.Stone--;
                }

                int x = (int)position.x;
                int y = (int)position.y;
                StableSpaces[x, y] = TileTypes.Stable;
                TilesToPlace.RemoveAt(0);
                _isPlacingSecondPartOfTile = TilesToPlace.Count > 0;
                if (_isPlacingSecondPartOfTile)
                {
                    _firstPartOfDouble = position;
                }
                else
                {
                    _firstPartOfDouble = new Vector2(-1, -1);
                }
                serverSocket.SetPlayerTileType(position, GetTileType(position, isForest), !isForest);
                return;
            }
            string[,] tileArea;
            if (isForest)
                tileArea = ForestSpaces;
            else
                tileArea = CaveSpaces;

            string oldTile = tileArea[(int)position.x, (int)position.y];
            string newTile = TilesToPlace.First();

            tileArea[(int)position.x, (int)position.y] = newTile;
            TilesToPlace.RemoveAt(0);

            //if this was a double fenced pasture, record it
            if (_isPlacingSecondPartOfTile && newTile == TileTypes.BigFence2)
            {
                _doubleFencedPastures.Add(_firstPartOfDouble);
                _doubleFencedPastures.Add(position);
            }

            _isPlacingSecondPartOfTile = TilesToPlace.Count > 0;
            if (_isPlacingSecondPartOfTile)
            {
                _firstPartOfDouble = position;
            }
            else
            {
                _firstPartOfDouble = new Vector2(-1, -1);
            }

            //apply any bonuses from this tile
            if (isForest)
            {
                if ((int)position.x == 1 && (int)position.y == 0)
                    foodGain++;
                if ((int)position.x == 0 && (int)position.y == 1)
                    pigsGain++;
                if ((int)position.x == 2 && (int)position.y == 3)
                    pigsGain++;
            }
            else
            {
                if (oldTile == TileTypes.DeepTunnel && newTile == TileTypes.RubyMine)
                    rubyGain++;
                if ((int)position.x == 1 && (int)position.y == 0)
                    foodGain++;
                if ((int)position.x == 2 && (int)position.y == 3)
                    foodGain += 2;
            }

            serverSocket.SetPlayerTileType(position, GetTileType(position, isForest), !isForest);
        }
        public void FieldPhase(IServerSocket _serverSocket, out int harvestedGrain, out int harvestedVeg)
        {
            harvestedGrain = 0;
            harvestedVeg = 0;
            List<Vector2> updatedFields = new List<Vector2>();

            //replace each 1 corn or 1 veg with zero, 2 with 1, 3 with 2, etc
            for (int x = 0; x < TileAreaWidth; x++)
            {
                for (int y = 0; y < TileAreaHeight; y++)
                {
                    if (ForestSpaces[x, y] == TileTypes.Field1Grain)
                    {
                        ForestSpaces[x, y] = TileTypes.Field;
                        harvestedGrain++;
                        updatedFields.Add(new Vector2(x, y));
                    }
                    if (ForestSpaces[x, y] == TileTypes.Field2Grain)
                    {
                        ForestSpaces[x, y] = TileTypes.Field1Grain;
                        harvestedGrain++;
                        updatedFields.Add(new Vector2(x, y));
                    }
                    if (ForestSpaces[x, y] == TileTypes.Field3Grain)
                    {
                        ForestSpaces[x, y] = TileTypes.Field2Grain;
                        harvestedGrain++;
                        updatedFields.Add(new Vector2(x, y));
                    }
                    if (ForestSpaces[x, y] == TileTypes.Field1Veg)
                    {
                        ForestSpaces[x, y] = TileTypes.Field;
                        harvestedVeg++;
                        updatedFields.Add(new Vector2(x, y));
                    }
                    if (ForestSpaces[x, y] == TileTypes.Field2Veg)
                    {
                        ForestSpaces[x, y] = TileTypes.Field1Veg;
                        harvestedVeg++;
                        updatedFields.Add(new Vector2(x, y));
                    }
                }
            }

            foreach (Vector2 position in updatedFields)
            {
                _serverSocket.SetPlayerTileType(position, GetTileType(position, true), false);
            }
        }
 public CavernaManager(IServerSocket serverSocket, int numPlayers)
 {
     _serverSocket = serverSocket;
     StartGame(numPlayers);
 }
        public void AutoArrangeAnimals(IServerSocket serverSocket, AnimalManager animalManager, bool triggerChoice, bool discardExcess, bool isBreeding)
        {
            //Entry room holds 2 of same type
            //Pasture holds 2 of same type
            //Large pasture holds 4 of same time
            //Stable on pasture doubles capacity
            //Stable on meadow holds 1 animal

            //Ore/Ruby mine -> 1 donkey each
            //Stable on forest holds 1 pig
            //Dogs go anywhere... but preferably on meadow/pasture
            //dog(s) on meadow holds dogs+1 sheep OR meadow capacity
            //dog(s) on pasture holder dogs+1 sheep OR pasture capacity

            //other areas exist as 'blocks'
            //dogs can cause these to be variable... there will be P*D combinations, where
            //P = number of meadows/pastures, D = number of dogs
            //maybe just do these if we have excess sheep... which will be allocated last anyway.

            List<AnimalHolder> animalsHolders = new List<AnimalHolder>();

            //add starting tile
            AnimalHolder startingTile = new AnimalHolder();
            startingTile.TileType = TileTypes.StartingTile;
            startingTile.genericCapacity = 2;
            startingTile.position = new Vector2(0f, 0f);
            startingTile.isCave = true;
            animalsHolders.Add(startingTile);

            //add single fenced areas
            List<Vector2> smallFencedAreas = GetMatchingForestTileSpaces(TileTypes.SmallFence);
            foreach (Vector2 smallPasture in smallFencedAreas)
            {
                AnimalHolder pasture = new AnimalHolder();
                pasture.TileType = TileTypes.SmallFence;
                pasture.isCave = false;
                pasture.genericCapacity = 2;
                pasture.position = smallPasture;
                if (StableSpaces[(int)smallPasture.x, (int)smallPasture.y] == TileTypes.Stable)
                    pasture.genericCapacity = pasture.genericCapacity*2;
                animalsHolders.Add(pasture);
            }

            //add double fenced areas
            for(int i=0; i< _doubleFencedPastures.Count; i+=2)
            {
                AnimalHolder pasture = new AnimalHolder();
                pasture.TileType = TileTypes.BigFence1;
                pasture.isCave = false;
                pasture.genericCapacity = 4;
                pasture.position = _doubleFencedPastures[i];
                if (StableSpaces[(int)_doubleFencedPastures[i].x, (int)_doubleFencedPastures[i].y] == TileTypes.Stable)
                    pasture.genericCapacity = pasture.genericCapacity * 2;
                if (StableSpaces[(int)_doubleFencedPastures[i+1].x, (int)_doubleFencedPastures[i+1].y] == TileTypes.Stable)
                    pasture.genericCapacity = pasture.genericCapacity * 2;
                animalsHolders.Add(pasture);
            }

            //add meadows with stables
            List<Vector2> meadows = GetMatchingForestTileSpaces(TileTypes.Clearing);
            foreach (Vector2 meadow in meadows)
            {
                AnimalHolder clearing = new AnimalHolder();
                clearing.TileType = TileTypes.Clearing;
                clearing.isCave = false;
                clearing.genericCapacity = 0;
                clearing.position = meadow;
                if (StableSpaces[(int)meadow.x, (int)meadow.y] == TileTypes.Stable)
                    clearing.genericCapacity = 1;
                animalsHolders.Add(clearing);
            }

            //add forests with stables
            List<Vector2> forestPositions = GetMatchingForestTileSpaces(null);
            foreach (Vector2 position in forestPositions)
            {
                AnimalHolder holder = new AnimalHolder();
                holder.TileType = null;
                holder.isCave = false;
                holder.genericCapacity = 0;
                holder.position = position;
                if (StableSpaces[(int)position.x, (int)position.y] == TileTypes.Stable)
                    holder.pigCapacity = 1;
                animalsHolders.Add(holder);
            }

            //add ore mines
            List<Vector2> oreMinePositions = GetMatchingCaveTileSpaces(TileTypes.OreMine);
            foreach (Vector2 position in oreMinePositions)
            {
                AnimalHolder holder = new AnimalHolder();
                holder.TileType = TileTypes.OreMine;
                holder.isCave = true;
                holder.donkeyCapacity = 1;
                holder.position = position;
                animalsHolders.Add(holder);
            }

            //add ruby mines
            List<Vector2> rubyMinePositions = GetMatchingCaveTileSpaces(TileTypes.RubyMine);
            foreach (Vector2 position in rubyMinePositions)
            {
                AnimalHolder holder = new AnimalHolder();
                holder.TileType = TileTypes.RubyMine;
                holder.isCave = true;
                holder.donkeyCapacity = 1;
                holder.position = position;
                animalsHolders.Add(holder);
            }

            //add special buildings
            List<Vector2> mixedDwellingPositions = GetMatchingCaveTileSpaces(BuildingTypes.MixedDwelling);
            foreach (Vector2 position in mixedDwellingPositions)
            {
                AnimalHolder holder = new AnimalHolder();
                holder.TileType = BuildingTypes.MixedDwelling;
                holder.isCave = true;
                holder.genericCapacity = 2;
                holder.position = position;
                animalsHolders.Add(holder);
            }
            List<Vector2> breakfastRoomPositions = GetMatchingCaveTileSpaces(BuildingTypes.BreakfastRoom);
            foreach (Vector2 position in breakfastRoomPositions)
            {
                AnimalHolder holder = new AnimalHolder();
                holder.TileType = BuildingTypes.BreakfastRoom;
                holder.isCave = true;
                holder.cowCapacity = 3;
                holder.position = position;
                animalsHolders.Add(holder);
            }
            List<Vector2> cuddleRoomPositions = GetMatchingCaveTileSpaces(BuildingTypes.CuddleRoom);
            foreach (Vector2 position in cuddleRoomPositions)
            {
                AnimalHolder holder = new AnimalHolder();
                holder.TileType = BuildingTypes.CuddleRoom;
                holder.isCave = true;
                holder.sheepCapacity = _player.GetDwarfStatus().Count;
                holder.position = position;
                animalsHolders.Add(holder);
            }

            //add whatever the dogs are doing

            int cowsToAllocate = animalManager.Cows;
            int pigsToAllocate = animalManager.Pigs;
            int donkeysToAllocate = animalManager.Donkeys;
            int sheepToAllocate = animalManager.Sheep;
            int dogsToAllocate = animalManager.Dogs;

            //Dogs spread between meadows as evenly as possible
            //sheepWatched = Math.Min(dogs, meadows)*2
            //if dogs > meadows
            //sheepWatched += dogs-meadows
            //e.g, 5 dogs 2 meadows --> 7 sheep
            //---> possible exception for stabled meadow... assign dogs to this last (generic capacity 1)
            //
            //If no meadows, dogs cluster in lowest capacity pasture to maximise extra sheep capacity
            //
            //If no pastures, dogs can live in the home dwelling or near the house or something
            //
            //When filling areas, do not assign sheep/generic areas until after all sheep only areas.
            //Then assign sheep only if there are MORE sheep than generic capacity (ie, extra space will get used)
            //Otherwise, treat as normal

            //ASSIGN DOGS
            if (dogsToAllocate > 0)
            {
                if (animalsHolders.Count(x => x.TileType == TileTypes.Clearing) > 0)
                {
                    List<AnimalHolder> clearings = animalsHolders.Where(x => x.TileType == TileTypes.Clearing).OrderBy(x => x.genericCapacity).ToList();
                    while (dogsToAllocate > 0)
                    {
                        foreach (AnimalHolder clearing in clearings)
                        {
                            clearing.AddDog(ref dogsToAllocate);
                        }
                    }
                }
                else if (animalsHolders.Count(x => x.TileType == TileTypes.SmallFence || x.TileType == TileTypes.BigFence1) > 0)
                {
                    AnimalHolder smallestCapacity = animalsHolders.Where(x => x.TileType == TileTypes.SmallFence || x.TileType == TileTypes.BigFence1).OrderBy(x => x.genericCapacity).First();
                    smallestCapacity.FillAnimals(ResourceTypes.Dogs, ref dogsToAllocate);
                }
                else
                {
                    //put them in the house
                    AnimalHolder tile = animalsHolders.First(x => x.TileType == TileTypes.StartingTile);
                    tile.FillAnimals(ResourceTypes.Dogs, ref dogsToAllocate);
                }
            }

            //FIRST PASS - areas only for specific animals

            while (cowsToAllocate > 0)
            {
                //first find spaces that only hold cows
                List<AnimalHolder> cowHolders = animalsHolders.FindAll(x => x.IsUnfilledCowHolder);
                if (cowHolders.Count > 0)
                {
                    cowHolders[0].FillAnimals(ResourceTypes.Cows, ref cowsToAllocate);
                    continue;
                }

                //nowhere to put them!
                break;
            }

            while (pigsToAllocate > 0)
            {
                //first find spaces that only hold pigs
                List<AnimalHolder> pigHolders = animalsHolders.FindAll(x => x.IsUnfilledPigHolder);
                if (pigHolders.Count > 0)
                {
                    pigHolders[0].FillAnimals(ResourceTypes.Pigs, ref pigsToAllocate);
                    continue;
                }

                //nowhere to put them!
                break;
            }

            while (donkeysToAllocate > 0)
            {
                //first find spaces that only hold donkeys
                List<AnimalHolder> donkeyHolders = animalsHolders.FindAll(x => x.IsUnfilledDonkeyHolder);
                if (donkeyHolders.Count > 0)
                {
                    donkeyHolders[0].FillAnimals(ResourceTypes.Donkeys, ref donkeysToAllocate);
                    continue;
                }

                //nowhere to put them!
                break;
            }

            //When filling areas, do not assign sheep & generic areas until after all sheep only areas.
            //Then assign sheep only if there are MORE sheep than generic capacity (ie, extra space will get used)
            while (sheepToAllocate > 0)
            {
                //first find spaces that ONLY hold sheep
                List<AnimalHolder> sheepHolders = animalsHolders.FindAll(x => x.IsUnfilledSheepHolder && x.genericCapacity ==0);
                if (sheepHolders.Count > 0)
                {
                    sheepHolders[0].FillAnimals(ResourceTypes.Sheep, ref sheepToAllocate);
                    continue;
                }

                //then places that will get more sheep assigned than generic capacity
                sheepHolders = animalsHolders.FindAll(x => x.IsUnfilledSheepHolder && sheepToAllocate > x.genericCapacity);
                if (sheepHolders.Count > 0)
                {
                    sheepHolders[0].FillAnimals(ResourceTypes.Sheep, ref sheepToAllocate);
                    continue;
                }

                //other places get assigned as normal
                break;
            }

            //SECOND PASS - take group with most animals, put in biggest pen. Repeat.
            bool fillMade = true;
            while (fillMade)
            {
                int maxAnimals = new[] {cowsToAllocate, pigsToAllocate, donkeysToAllocate, sheepToAllocate}.Max();
                fillMade = false;

                if (cowsToAllocate > 0 && cowsToAllocate == maxAnimals)
                {
                    //find the space that holds most cows, and put them there
                    List<AnimalHolder> primaryHolders =
                        animalsHolders.FindAll(x => x.RemainingCowCapacity > 0).OrderByDescending(x => x.RemainingCowCapacity)
                        .ToList();
                    if (primaryHolders.Count > 0)
                    {
                        primaryHolders[0].FillAnimals(ResourceTypes.Cows, ref cowsToAllocate);
                        fillMade = true;
                    }
                }
                else if (pigsToAllocate > 0 && pigsToAllocate == maxAnimals)
                {
                    //find the space that holds most cows, and put them there
                    List<AnimalHolder> primaryHolders =
                        animalsHolders.FindAll(x => x.RemainingPigCapacity > 0).OrderByDescending(x => x.RemainingPigCapacity)
                        .ToList();
                    if (primaryHolders.Count > 0)
                    {
                        primaryHolders[0].FillAnimals(ResourceTypes.Pigs, ref pigsToAllocate);
                        fillMade = true;
                    }
                }
                else if (donkeysToAllocate > 0 && donkeysToAllocate == maxAnimals)
                {
                    //find the space that holds most cows, and put them there
                    List<AnimalHolder> primaryHolders =
                        animalsHolders.FindAll(x => x.RemainingDonkeyCapacity > 0).OrderByDescending(x => x.RemainingDonkeyCapacity)
                        .ToList();
                    if (primaryHolders.Count > 0)
                    {
                        primaryHolders[0].FillAnimals(ResourceTypes.Donkeys, ref donkeysToAllocate);
                        fillMade = true;
                    }
                }
                else if (sheepToAllocate > 0 && sheepToAllocate == maxAnimals)
                {
                    //find the space that holds most cows, and put them there
                    List<AnimalHolder> primaryHolders =
                        animalsHolders.FindAll(x => x.RemainingSheepCapacity > 0).OrderByDescending(x => x.RemainingSheepCapacity)
                        .ToList();
                    if (primaryHolders.Count > 0)
                    {
                        primaryHolders[0].FillAnimals(ResourceTypes.Sheep, ref sheepToAllocate);
                        fillMade = true;
                    }
                }
            }

            //now draw it to the screen
            foreach (AnimalHolder holder in animalsHolders)
            {
                serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Dogs, 0);
                serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Sheep, 0);
                serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Donkeys, 0);
                serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Pigs, 0);
                serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Cows, 0);

                if (holder.GetDogs() > 0)
                    serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Dogs, holder.GetDogs());
                if (holder.GetSheep() > 0)
                    serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Sheep, holder.GetSheep());
                if (holder.GetDonkeys() > 0)
                    serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Donkeys, holder.GetDonkeys());
                if (holder.GetPigs() > 0)
                    serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Pigs, holder.GetPigs());
                if (holder.GetCows() > 0)
                    serverSocket.SetTileAnimals(holder.position, holder.isCave, ResourceTypes.Cows, holder.GetCows());
            }

            //did we have leftovers? if so, need to warn the player
            ArrangeAnimalsTriggered = false;
            if (cowsToAllocate + pigsToAllocate + donkeysToAllocate + sheepToAllocate == 0)
                return;

            ArrangeAnimalsTriggered = true;

            if (discardExcess)
            {
                //do not trigger the normal checks with this, use aninal manager to avoid
                animalManager.Cows -= cowsToAllocate;
                animalManager.Pigs -= pigsToAllocate;
                animalManager.Donkeys -= donkeysToAllocate;
                animalManager.Sheep -= sheepToAllocate;
            }

            if (!triggerChoice)
                return;

            string result = "Unassigned animals: ";
            if (cowsToAllocate > 0)
                result += cowsToAllocate + " cows, ";
            if (pigsToAllocate > 0)
                result += pigsToAllocate + " pigs, ";
            if (donkeysToAllocate > 0)
                result += donkeysToAllocate + " donkeys, ";
            if (sheepToAllocate > 0)
                result += sheepToAllocate + " sheep, ";

            List<string> options = new List<string>();
            options.Add(DiscardActions.DiscardAllUnassignedAnimals);

            //are we in the breeding phase?
            if (isBreeding)
            {
                if (animalManager.Cows > 0)
                    options.Add(DiscardActions.DiscardCow);
                if (animalManager.Pigs > 0)
                    options.Add(DiscardActions.DiscardPig);
                if (animalManager.Donkeys > 0)
                    options.Add(DiscardActions.DiscardDonkey);
                if (animalManager.Sheep > 0)
                    options.Add(DiscardActions.DiscardSheep);
            }
            else
            {
                if (HasTile(BuildingTypes.SlaughteringCave))
                {
                    if (animalManager.Cows > 0)
                        options.Add(FoodActions.SlaughteringCaveConvertCow);
                    if (animalManager.Pigs > 0)
                        options.Add(FoodActions.SlaughteringCaveConvertPig);
                    if (animalManager.Donkeys > 1)
                        options.Add(FoodActions.SlaughteringCaveConvertDonkeyPair);
                    if (animalManager.Donkeys > 0)
                        options.Add(FoodActions.SlaughteringCaveConvertDonkey);
                    if (animalManager.Sheep > 0)
                        options.Add(FoodActions.SlaughteringCaveConvertSheep);
                }
                else
                {
                    if (animalManager.Cows > 0)
                        options.Add(FoodActions.ConvertCow);
                    if (animalManager.Pigs > 0)
                        options.Add(FoodActions.ConvertPig);
                    if (animalManager.Donkeys > 1)
                        options.Add(FoodActions.ConvertDonkeyPair);
                    if (animalManager.Donkeys > 0)
                        options.Add(FoodActions.ConvertDonkey);
                    if (animalManager.Sheep > 0)
                        options.Add(FoodActions.ConvertSheep);
                }
            }

            serverSocket.GetPlayerChoice("playerID", "Allocate Animals", result, options);
        }
 public void SowVeg(IServerSocket serverSocket)
 {
     for (int x = 0; x < TileAreaWidth; x++)
     {
         for (int y = 0; y < TileAreaHeight; y++)
         {
             if (ForestSpaces[x, y] == TileTypes.Field)
             {
                 ForestSpaces[x, y] = TileTypes.Field2Veg;
                 serverSocket.SetPlayerTileType(new Vector2(x, y), GetTileType(new Vector2(x, y), true), false);
                 return;
             }
         }
     }
 }
 public void SetBuildingTileAt(IServerSocket serverSocket, Vector2 position, string buildingType)
 {
     CaveSpaces[(int)position.x, (int)position.y] = buildingType;
     serverSocket.SetPlayerTileType(position, GetTileType(position, false), true);
 }