Пример #1
0
 public void AcceptClient(string idlURL, ClientHandler handler)
 {
     // TODO(rryk): Load IDL from idlURL, load info about port number.
       // TODO(rryk): Listen for new clients on that port number. For each client execute handler
       // on a new thread.
       throw new NotImplementedException("AcceptClient is not implemented");
 }
Пример #2
0
        public void StartListening()
        {
            listener = new TcpListenerWrapper(Config.ListenPort);
            listener.OnClientConnected += new TcpListenerWrapper.ClientConnectedDelegate(listener_OnClientConnected);

            clients = new ClientHandler();
            clients.UserPacketReceived += new ClientHandler.UserPacketReceivedDelegate(HandlePacket);
            clients.UserDisconnected += new ClientHandler.UserDisconnectedDelegate(clients_UserDisconnected);

            listener.Listen(Config.MaxConnectionsBacklog, Config.MaxClientSendBacklog);
        }
        public void ConnectToMultiplayer()
        {
            Client = new ClientHandler();
            Client.ReceivedTcp += Client_ReceivedTcp;
            Client.AuthRequested += Client_AuthRequested;
            Client.Disconnected += Client_Disconnected;
            Client.SynchronizingObject = this;

            Client.Connect(IPAddress.Parse(ip), port, Connect);
            Online = true;
        }
Пример #4
0
Файл: Server.cs Проект: fry/d3
		public void Start() {
			var listener = new TcpListener(IPAddress.Any, port);
			listener.Start();

			Debug.WriteLine("Listening on {0}", listener.LocalEndpoint);

			while (true) {
				var socket = listener.AcceptTcpClient();
				Debug.WriteLine("Connection from {0}", socket.Client.RemoteEndPoint);
				var client = new ClientHandler(ImportRegistry, ExportRegistry);
				client.Start(socket);
			}
		}
Пример #5
0
	public void RunServerImpl()
	{
		//yield return null;

		TcpListener tcpListener = null;
		
		try
		{
			//ip주소를 나타내는 객체 생성. TcpListener생성시 인자로 사용
			IPAddress ipAd = IPAddress.Parse("127.0.0.1");
			
			//TcpListener class를 이용하여 클라이언트 연결 받아 들임
			tcpListener = new TcpListener(ipAd, TestServer.PORT);
			tcpListener.Start();
			
			//Console.WriteLine("멀티스레드 Test 창 :Waiting for connections...");
			Debug.Log("S: Waiting for connections.. \n");

			while (true)
			{
				//accepting the connection
				Socket client = tcpListener.AcceptSocket();
				Debug.Log(string.Format("S: Accepted socket {0} \n", client.Connected));
				
				ClientHandler cHandler = new ClientHandler();
				//passing calue to the thread class
				cHandler.clientSocket = client;
				
				//creating a new thread for the client
				Thread clientThread = new Thread(new ThreadStart(cHandler.runClient));
				clientThread.Start();
			}
		}
		catch (Exception exp)
		{
			//Console.WriteLine("Exception :" + exp);
			Debug.Log("S: Exception :" + exp);
		}
		finally
		{
			tcpListener.Stop();
		}
	}
Пример #6
0
 public void Broadcast(ClientHandler client, string message)
 {
     foreach (ClientHandler tmpClient in clients)
     {
         if (tmpClient != client)
         {
             NetworkStream n = tmpClient.tcpclient.GetStream();
             BinaryWriter w = new BinaryWriter(n);
             w.Write(message);
             w.Flush();
         }
         else if (clients.Count() == 1)
         {
             NetworkStream n = tmpClient.tcpclient.GetStream();
             BinaryWriter w = new BinaryWriter(n);
             w.Write("Sorry, you are alone...");
             w.Flush();
         }
     }
 }
Пример #7
0
        public void HandleDataReceivedTest()
        {
            var ServerManager = new ServerManager();
            var TestTcpTestServer = TcpTestServer.Create();
            var TestBaseClientHandler = new ClientHandler(ServerManager, TestTcpTestServer.LocalTcpClient);
            TestBaseClientHandler.StartReceivingData();

            var ClientClientStream = TestTcpTestServer.RemoteTcpClient.GetStream();

            // Client send a GetVersion request.
            var PacketToSend = new Packet(Packet.PacketType.GetVersion);
            PacketToSend.WritePacketTo(ClientClientStream);

            Packet PacketReceived = Packet.FromStream(ClientClientStream);

            // Client receives a GetVersion response from the server.
            Assert.AreEqual(
                ServerManager.Version.ToString(),
                PacketReceived.Stream.ReadStruct<ServerManager.VersionStruct>().ToString()
            );
        }
Пример #8
0
        public static void SendServerSettings(ClientObject client)
        {
            int           numberOfKerbals         = Directory.GetFiles(Path.Combine(Server.universeDirectory, "Kerbals")).Length;
            int           numberOfVessels         = Directory.GetFiles(Path.Combine(Server.universeDirectory, "Vessels")).Length;
            int           numberOfScenarioModules = Directory.GetFiles(Path.Combine(Server.universeDirectory, "Scenarios", client.playerName)).Length;
            ServerMessage newMessage = new ServerMessage();

            newMessage.type = ServerMessageType.SERVER_SETTINGS;
            using (MessageWriter mw = new MessageWriter())
            {
                mw.Write <int>((int)Settings.settingsStore.warpMode);
                mw.Write <int>((int)Settings.settingsStore.gameMode);
                mw.Write <bool>(Settings.settingsStore.cheats);
                //Tack the amount of kerbals, vessels and scenario modules onto this message
                mw.Write <int>(numberOfKerbals);
                mw.Write <int>(numberOfVessels);
                //mw.Write<int>(numberOfScenarioModules);
                mw.Write <int>(Settings.settingsStore.screenshotHeight);
                mw.Write <int>(Settings.settingsStore.numberOfAsteroids);
                mw.Write <string>(Settings.settingsStore.consoleIdentifier);
                newMessage.data = mw.GetMessageBytes();
            }
            ClientHandler.SendToClient(client, newMessage, true);
        }
Пример #9
0
 public static void SendAllSubspaces(ClientObject client)
 {
     //Send all the locks.
     foreach (KeyValuePair <int, Subspace> subspace in subspaces)
     {
         ServerMessage newMessage = new ServerMessage();
         newMessage.type = ServerMessageType.WARP_CONTROL;
         using (MessageWriter mw = new MessageWriter())
         {
             mw.Write <int>((int)WarpMessageType.NEW_SUBSPACE);
             mw.Write <int>(subspace.Key);
             mw.Write <long>(subspace.Value.serverClock);
             mw.Write <double>(subspace.Value.planetTime);
             mw.Write <float>(subspace.Value.subspaceSpeed);
             newMessage.data = mw.GetMessageBytes();
         }
         ClientHandler.SendToClient(client, newMessage, true);
     }
     //Tell the player "when" everyone is.
     foreach (ClientObject otherClient in ClientHandler.GetClients())
     {
         if (otherClient.authenticated && (otherClient.playerName != client.playerName))
         {
             ServerMessage newMessage = new ServerMessage();
             newMessage.type = ServerMessageType.WARP_CONTROL;
             using (MessageWriter mw = new MessageWriter())
             {
                 mw.Write <int>((int)WarpMessageType.CHANGE_SUBSPACE);
                 mw.Write <string>(otherClient.playerName);
                 mw.Write <int>(otherClient.subspace);
                 newMessage.data = mw.GetMessageBytes();
             }
             ClientHandler.SendToClient(client, newMessage, true);
         }
     }
 }
Пример #10
0
        private static void HandleChangeWarp(ClientObject client, bool physWarp, int rateIndex, long serverClock, double planetTime)
        {
            ServerMessage newMessage = new ServerMessage();

            newMessage.type = ServerMessageType.WARP_CONTROL;
            using (MessageWriter mw = new MessageWriter())
            {
                mw.Write <int>((int)WarpMessageType.CHANGE_WARP);
                mw.Write <string>(client.playerName);
                mw.Write <bool>(physWarp);
                mw.Write <int>(rateIndex);
                mw.Write <long>(serverClock);
                mw.Write <double>(planetTime);
                newMessage.data = mw.GetMessageBytes();
            }
            if (Settings.settingsStore.warpMode == WarpMode.MCW_LOWEST)
            {
                PlayerWarpRate clientWarpRate = null;

                if (!warpList.ContainsKey(client.playerName))
                {
                    clientWarpRate = new PlayerWarpRate();
                    warpList.Add(client.playerName, clientWarpRate);
                }
                else
                {
                    clientWarpRate = warpList[client.playerName];
                }
                clientWarpRate.isPhysWarp  = physWarp;
                clientWarpRate.rateIndex   = rateIndex;
                clientWarpRate.serverClock = serverClock;
                clientWarpRate.planetTime  = planetTime;
                HandleLowestRateChange(client);
            }
            ClientHandler.SendToAll(client, newMessage, true);
        }
Пример #11
0
        public Viewport(IRenderTarget target, BrowserDelegate browserDelegate)
        {
            _target = target;
            _target.TargetClosing += OnTargetClosing;
            _target.TargetClosed += OnTargetClosed;
            _target.TargetSizeChanged += OnTargetSizeChanged;

            _handler = new ClientHandler(browserDelegate);

            _settings = new BrowserSettings {
                IsFileAccessfromUrlsAllowed = false,
                IsWebSecurityDisabled = false,
                IsUniversalAccessFromFileUrlsAllowed = false,
                IsUserStyleSheetEnabled = false
            };

            if (Platform.IsLinux) {
                _resizer = new LinuxWindowResizer();
            }

            if (Platform.IsWindows) {
                _resizer = new WindowsWindowResizer();
            }
        }
Пример #12
0
            public void Run()
            {
                Console.WriteLine("IP: " + GetLocalIPAddress());
                int port = 5000;

                Console.WriteLine("Port: " + port);
                TcpListener listener = new TcpListener(IPAddress.Any, port);

                Console.WriteLine("Server up and running, waiting for messages...");

                try
                {
                    listener.Start();

                    while (true)
                    {
                        TcpClient     c         = listener.AcceptTcpClient();
                        ClientHandler newClient = new ClientHandler(c, this);
                        clients.Add(newClient);

                        Thread clientThread = new Thread(newClient.Run);
                        clientThread.Start();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (listener != null)
                    {
                        listener.Stop();
                    }
                }
            }
Пример #13
0
    public Task ExpectedKeysAreInFeatures()
    {
        var handler = new ClientHandler(new PathString("/A/Path/"), new InspectingApplication(features =>
        {
            Assert.True(features.Get <IHttpRequestLifetimeFeature>().RequestAborted.CanBeCanceled);
            Assert.Equal(HttpProtocol.Http11, features.Get <IHttpRequestFeature>().Protocol);
            Assert.Equal("GET", features.Get <IHttpRequestFeature>().Method);
            Assert.Equal("https", features.Get <IHttpRequestFeature>().Scheme);
            Assert.Equal("/A/Path", features.Get <IHttpRequestFeature>().PathBase);
            Assert.Equal("/and/file.txt", features.Get <IHttpRequestFeature>().Path);
            Assert.Equal("?and=query", features.Get <IHttpRequestFeature>().QueryString);
            Assert.NotNull(features.Get <IHttpRequestFeature>().Body);
            Assert.NotNull(features.Get <IHttpRequestFeature>().Headers);
            Assert.NotNull(features.Get <IHttpResponseFeature>().Headers);
            Assert.NotNull(features.Get <IHttpResponseBodyFeature>().Stream);
            Assert.Equal(200, features.Get <IHttpResponseFeature>().StatusCode);
            Assert.Null(features.Get <IHttpResponseFeature>().ReasonPhrase);
            Assert.Equal("example.com", features.Get <IHttpRequestFeature>().Headers["host"]);
            Assert.NotNull(features.Get <IHttpRequestLifetimeFeature>());
        }));
        var httpClient = new HttpClient(handler);

        return(httpClient.GetAsync("https://example.com/A/Path/and/file.txt?and=query"));
    }
Пример #14
0
    public Task ExceptionFromOnStartingWithErrorHandlerIsReported()
    {
        var handler = new ClientHandler(PathString.Empty, new DummyApplication(async context =>
        {
            context.Response.OnStarting(() =>
            {
                throw new InvalidOperationException(new string('a', 1024 * 32));
            });
            try
            {
                await context.Response.WriteAsync("Hello World");
            }
            catch (Exception ex)
            {
                // This is no longer the first write, so it doesn't trigger OnStarting again.
                // The exception is large enough that it fills the pipe and stalls.
                await context.Response.WriteAsync(ex.ToString());
            }
        }));
        var httpClient = new HttpClient(handler);

        return(Assert.ThrowsAsync <InvalidOperationException>(() => httpClient.GetAsync("https://example.com/",
                                                                                        HttpCompletionOption.ResponseHeadersRead)));
    }
Пример #15
0
    public async Task ClientDisposalCloses()
    {
        var block   = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var handler = new ClientHandler(PathString.Empty, new DummyApplication(async context =>
        {
            context.Response.Headers["TestHeader"] = "TestValue";
            await context.Response.Body.FlushAsync();
            await block.Task;
        }));
        var httpClient = new HttpClient(handler);
        HttpResponseMessage response = await httpClient.GetAsync("https://example.com/",
                                                                 HttpCompletionOption.ResponseHeadersRead);

        Assert.Equal("TestValue", response.Headers.GetValues("TestHeader").First());
        Stream responseStream = await response.Content.ReadAsStreamAsync();

        Task <int> readTask = responseStream.ReadAsync(new byte[100], 0, 100);

        Assert.False(readTask.IsCompleted);
        responseStream.Dispose();
        await Assert.ThrowsAsync <OperationCanceledException>(() => readTask.DefaultTimeout());

        block.SetResult();
    }
Пример #16
0
    public async Task ResubmitRequestWorks()
    {
        int requestCount = 1;
        var handler      = new ClientHandler(PathString.Empty, new DummyApplication(async context =>
        {
            int read = await context.Request.Body.ReadAsync(new byte[100], 0, 100);
            Assert.Equal(11, read);

            context.Response.Headers["TestHeader"] = "TestValue:" + requestCount++;
        }));

        HttpMessageInvoker invoker = new HttpMessageInvoker(handler);
        HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, "https://example.com/");

        message.Content = new StringContent("Hello World");

        HttpResponseMessage response = await invoker.SendAsync(message, CancellationToken.None);

        Assert.Equal("TestValue:1", response.Headers.GetValues("TestHeader").First());

        response = await invoker.SendAsync(message, CancellationToken.None);

        Assert.Equal("TestValue:2", response.Headers.GetValues("TestHeader").First());
    }
Пример #17
0
        private void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                var       server = (TcpListener)ar.AsyncState;
                TcpClient tcp    = server.EndAcceptTcpClient(ar);
                tcp.ReceiveBufferSize = Config.CHUNK_SIZE;
                tcp.SendTimeout       = Config.SEND_TIMEOUT;
                tcp.ReceiveTimeout    = tcp.SendTimeout;
                tcp.SendBufferSize    = Config.CHUNK_SIZE;

                server.BeginAcceptTcpClient(AcceptCallback, server);

                if (tcp != null)
                {
                    // An incoming connection needs to be processed.
                    var ch = new ClientHandler(tcp, _processPayload);
                    _ConnectionPool.Enqueue(ch);
                }
            }
            catch
            {
            }
        }
Пример #18
0
 public static void HandleKerbalsRequest(ClientObject client)
 {
     //The time sensitive SYNC_TIME is over by this point.
     using (MessageWriter mw = new MessageWriter())
     {
         mw.Write <string>(client.playerName);
         ServerMessage joinMessage = new ServerMessage();
         joinMessage.type = ServerMessageType.PLAYER_JOIN;
         joinMessage.data = mw.GetMessageBytes();
         ClientHandler.SendToAll(client, joinMessage, true);
     }
     Messages.ServerSettings.SendServerSettings(client);
     Messages.WarpControl.SendSetSubspace(client);
     Messages.WarpControl.SendAllSubspaces(client);
     Messages.PlayerColor.SendAllPlayerColors(client);
     Messages.PlayerStatus.SendAllPlayerStatus(client);
     Messages.ScenarioData.SendScenarioModules(client);
     Messages.WarpControl.SendAllReportedSkewRates(client);
     Messages.CraftLibrary.SendCraftList(client);
     Messages.Chat.SendPlayerChatChannels(client);
     Messages.LockSystem.SendAllLocks(client);
     Messages.AdminSystem.SendAllAdmins(client);
     //Send kerbals
     lock (Server.universeSizeLock)
     {
         string[] kerbalFiles = Directory.GetFiles(Path.Combine(Server.universeDirectory, "Kerbals"));
         foreach (string kerbalFile in kerbalFiles)
         {
             string kerbalName = Path.GetFileNameWithoutExtension(kerbalFile);
             byte[] kerbalData = File.ReadAllBytes(kerbalFile);
             SendKerbal(client, kerbalName, kerbalData);
         }
         DarkLog.Debug("Sending " + client.playerName + " " + kerbalFiles.Length + " kerbals...");
     }
     SendKerbalsComplete(client);
 }
Пример #19
0
        public static void HandleWarpControl(ClientObject client, byte[] messageData)
        {
            ServerMessage newMessage = new ServerMessage();

            newMessage.type = ServerMessageType.WARP_CONTROL;
            newMessage.data = messageData;
            using (MessageReader mr = new MessageReader(messageData))
            {
                WarpMessageType warpType   = (WarpMessageType)mr.Read <int>();
                string          fromPlayer = mr.Read <string>();
                if (fromPlayer == client.playerName)
                {
                    if (warpType == WarpMessageType.NEW_SUBSPACE)
                    {
                        int newSubspaceID = mr.Read <int>();
                        if (subspaces.ContainsKey(newSubspaceID))
                        {
                            DarkLog.Debug("Kicked for trying to create an existing subspace");
                            Messages.ConnectionEnd.SendConnectionEnd(client, "Kicked for trying to create an existing subspace");
                            return;
                        }
                        else
                        {
                            Subspace newSubspace = new Subspace();
                            newSubspace.serverClock   = mr.Read <long>();
                            newSubspace.planetTime    = mr.Read <double>();
                            newSubspace.subspaceSpeed = mr.Read <float>();
                            subspaces.Add(newSubspaceID, newSubspace);
                            client.subspace = newSubspaceID;
                            SaveLatestSubspace();
                        }
                    }
                    if (warpType == WarpMessageType.CHANGE_SUBSPACE)
                    {
                        client.subspace = mr.Read <int>();
                    }
                    if (warpType == WarpMessageType.REPORT_RATE)
                    {
                        int reportedSubspace = mr.Read <int>();
                        if (client.subspace != reportedSubspace)
                        {
                            DarkLog.Debug("Warning, setting client " + client.playerName + " to subspace " + client.subspace);
                            client.subspace = reportedSubspace;
                        }
                        float newSubspaceRate = mr.Read <float>();
                        client.subspaceRate = newSubspaceRate;
                        foreach (ClientObject otherClient in ClientHandler.GetClients())
                        {
                            if (otherClient.authenticated && otherClient.subspace == reportedSubspace)
                            {
                                if (newSubspaceRate > otherClient.subspaceRate)
                                {
                                    newSubspaceRate = otherClient.subspaceRate;
                                }
                            }
                        }
                        if (newSubspaceRate < 0.3f)
                        {
                            newSubspaceRate = 0.3f;
                        }
                        if (newSubspaceRate > 1f)
                        {
                            newSubspaceRate = 1f;
                        }
                        //Relock the subspace if the rate is more than 3% out of the average
                        if (Math.Abs(subspaces[reportedSubspace].subspaceSpeed - newSubspaceRate) > 0.03f)
                        {
                            UpdateSubspace(reportedSubspace);
                            subspaces[reportedSubspace].subspaceSpeed = newSubspaceRate;
                            ServerMessage relockMessage = new ServerMessage();
                            relockMessage.type = ServerMessageType.WARP_CONTROL;
                            using (MessageWriter mw = new MessageWriter())
                            {
                                mw.Write <int>((int)WarpMessageType.RELOCK_SUBSPACE);
                                mw.Write <string>(Settings.settingsStore.consoleIdentifier);
                                mw.Write <int>(reportedSubspace);
                                mw.Write <long>(subspaces[reportedSubspace].serverClock);
                                mw.Write <double>(subspaces[reportedSubspace].planetTime);
                                mw.Write <float>(subspaces[reportedSubspace].subspaceSpeed);
                                relockMessage.data = mw.GetMessageBytes();
                            }
                            SaveLatestSubspace();
                            //DarkLog.Debug("Subspace " + client.subspace + " locked to " + newSubspaceRate + "x speed.");
                            ClientHandler.SendToClient(client, relockMessage, true);
                            ClientHandler.SendToAll(client, relockMessage, true);
                        }
                    }
                }
                else
                {
                    DarkLog.Debug(client.playerName + " tried to send an update for " + fromPlayer + ", kicking.");
                    Messages.ConnectionEnd.SendConnectionEnd(client, "Kicked for sending an update for another player");
                    return;
                }
            }
            ClientHandler.SendToAll(client, newMessage, true);
        }
Пример #20
0
 private CDNIndexHandler(ClientHandler client)
 {
     m_client = client;
 }
Пример #21
0
 public abstract IClient AddHandler(ClientType type, ClientHandler handler);
Пример #22
0
 public Client(ClientHandler handler, string host, int port)
 {
     Handler = handler;
 }
 void Respond(Request r)
 {
     ClientHandler handler;
     if (!_handlersByClientId.TryGetValue (r.ClientId, out handler)) {
         handler = new ClientHandler (r.ClientId, this);
         _handlersByClientId.Add (r.ClientId, handler);
     }
     handler.Respond (r);
 }
Пример #24
0
		public ChannelOwnerImpl(ClientHandler client) {
			this.client = client;
		}
Пример #25
0
        public void TestInit()
        {
            ClientHandler Handler = new ClientHandler();

            PaymentCheck = new EazySDK.Utilities.PaymentPostChecks();
        }
Пример #26
0
		public ConnectionServiceImpl(ClientHandler client) {
			this.client = client;
		}
Пример #27
0
		public AuthenticationServerImpl(ClientHandler client) {
			this.client = client;
		}
            public Subscription(ClientHandler client, SqlQuery query)
            {
                Id = System.Threading.Interlocked.Increment(ref _nextId).ToString();

                Client = client;
                Query = query;
            }
            public Subscription Subscribe(ClientHandler client)
            {
                Subscription sub = null;
                lock (_subsLock) {
                    if (!_subsByClientId.TryGetValue(client.ClientId, out sub)) {

                        sub = new Subscription(client, Query);

                        _subsByClientId[client.ClientId] = sub;
                        _subsById[sub.Id] = sub;
                    }
                }
                return sub;
            }
 void Unsubscribe(ClientHandler client, string subId)
 {
     Subscription sub = null;
     lock (_subsLock) {
         _subs.TryGetValue(subId, out sub);
         if (sub != null) {
             _subs.Remove(subId);
         }
     }
     if (sub != null) {
         var info = GetQueryInfo(sub.Query);
         info.Unsubscribe(sub);
     }
 }
 Subscription Subscribe(ClientHandler client, SqlQuery query)
 {
     var info = GetQueryInfo(query);
     var sub = info.Subscribe(client);
     lock (_subsLock) {
         if (!_subs.ContainsKey(sub.Id)) {
             _subs.Add(sub.Id, sub);
         }
     }
     return sub;
 }
Пример #32
0
 public CDNConfig(ClientHandler client, Stream?stream) : base(client, stream)
 {
 }
Пример #33
0
 public void HandleMessage(IncomingMessage message, ClientHandler clientHandler)
 {
     // Just checking if connection is alive
 }
Пример #34
0
 public void Enqueue(ClientHandler client)
 {
     SyncdQ.Enqueue(client) ;
 }
 public ClientHandlerFactory(ClientHandler.messageReceivedCallback mrc)
 {
     this.mrc = mrc;
 }
Пример #36
0
		public UserManagerServiceImpl(ClientHandler client) {
			this.client = client;
		}
Пример #37
0
        public ProductHandler_MNDX(ClientHandler client, Stream stream)
        {
            Handler = client;
            using (var reader = new BinaryReader(stream))
            {
                var header = reader.Read <MNDXHeader>();

                if (header.Signature != CASC_MNDX_SIGNATURE || header.FormatVersion > 2 || header.FormatVersion < 1)
                {
                    throw new Exception("invalid root file");
                }

                if (header.HeaderVersion == 2)
                {
                    var build1 = reader.ReadInt32(); // build number
                    var build2 = reader.ReadInt32(); // build number
                }

                var MarInfoOffset     = reader.ReadInt32();                        // Offset of the first MAR entry info
                var MarInfoCount      = reader.ReadInt32();                        // Number of the MAR info entries
                var MarInfoSize       = reader.ReadInt32();                        // Size of the MAR info entry
                var MndxEntriesOffset = reader.ReadInt32();
                var MndxEntriesTotal  = reader.ReadInt32();                        // Total number of MNDX root entries
                var MndxEntriesValid  = reader.ReadInt32();                        // Number of valid MNDX root entries
                var MndxEntrySize     = reader.ReadInt32();                        // Size of one MNDX root entry

                if (MarInfoCount > CASC_MAX_MAR_FILES || MarInfoSize != Marshal.SizeOf <MARInfo>())
                {
                    throw new Exception("invalid root file (1)");
                }

                for (var i = 0; i < MarInfoCount; i++)
                {
                    stream.Position = MarInfoOffset + (MarInfoSize * i);

                    var marInfo = reader.Read <MARInfo>();

                    stream.Position = marInfo.MarDataOffset;

                    MarFiles[i] = new MARFileNameDB(reader);

                    if (stream.Position != marInfo.MarDataOffset + marInfo.MarDataSize)
                    {
                        throw new Exception("MAR parsing error!");
                    }
                }

                stream.Position = MndxEntriesOffset;

                CASC_ROOT_ENTRY_MNDX?prevEntry = null;

                for (var i = 0; i < MndxEntriesTotal; i++)
                {
                    CASC_ROOT_ENTRY_MNDX entry = new CASC_ROOT_ENTRY_MNDX();

                    if (prevEntry != null)
                    {
                        prevEntry.Next = entry;
                    }

                    prevEntry      = entry;
                    entry.Flags    = reader.ReadInt32();
                    entry.MD5      = reader.Read <CKey>();
                    entry.FileSize = reader.ReadInt32();
                    mndxRootEntries.Add(i, entry);
                }

                mndxRootEntriesValid = new Dictionary <int, CASC_ROOT_ENTRY_MNDX>();

                var ValidEntryCount = 1; // edx
                var index           = 0;

                mndxRootEntriesValid[index++] = mndxRootEntries[0];

                for (var i = 0; i < MndxEntriesTotal; i++)
                {
                    if (ValidEntryCount >= MndxEntriesValid)
                    {
                        break;
                    }

                    if ((mndxRootEntries[i].Flags & 0x80000000) != 0)
                    {
                        mndxRootEntriesValid[index++] = mndxRootEntries[i + 1];

                        ValidEntryCount++;
                    }
                }


                Logger.Info("MNDX", "loading file names...");

                Regex regex          = new Regex("\\w{4}(?=\\.(storm|sc2)(data|assets))", RegexOptions.Compiled);
                var   packagesLocale = new Dictionary <int, Locale>();
                foreach (var result in MarFiles[0].EnumerateFiles())
                {
                    Packages.Add(result.FileNameIndex, result.FoundPath);

                    Match match = regex.Match(result.FoundPath);

                    if (match.Success)
                    {
                        var localeStr = match.Value;

                        if (!Enum.TryParse(localeStr, true, out Locale locale))
                        {
                            locale = Locale.All;
                        }

                        packagesLocale.Add(result.FileNameIndex, locale);
                    }
                    else
                    {
                        packagesLocale.Add(result.FileNameIndex, Locale.All);
                    }
                }

                Packages      = Packages.OrderByDescending(x => x.Value.Length).ToDictionary(x => x.Key, x => x.Value);
                PackagesValue = Packages.ToDictionary(x => x.Value, x => x.Key);

                foreach (var result in MarFiles[2].EnumerateFiles())
                {
                    var file    = result.FoundPath;
                    var package = FindMNDXPackage(file);
                    var entry   = new MNDXEntry
                    {
                        Path   = file,
                        Locale = packagesLocale[package],
                        Key    = FindMNDXInfo(file, package).MD5
                    };
                    Entries.Add(entry);
                }
            }
        }
Пример #38
0
		public PresenceServiceImpl(ClientHandler client) {
			this.client = client;
		}
Пример #39
0
 public Client(ClientHandler handler)
 {
     Handler = handler;
 }
Пример #40
0
 public void DisconnectClient(ClientHandler client)
 {
     clients.Remove(client);
     Console.WriteLine("Client X has left the building...");
     Broadcast(client, "Client X has left the building...");
 }
Пример #41
0
 private void Connection_OnConnectionClosed(SharpPcap.PosixTimeval timeval, TcpConnection connection, TcpPacket tcp, TcpConnection.CloseType closeType)
 {
     TcpConnection.OnPacketReceived   -= Connection_OnPacketReceived;
     TcpConnection.OnConnectionClosed -= Connection_OnConnectionClosed;
     ClientHandler.RemoveGameClient(this);
 }
Пример #42
0
            public void Run()
            {
                TcpListener listener = new TcpListener(IPAddress.Any, 5000);
                Console.WriteLine("Server up and running, waiting for messages...");

                try
                {
                    listener.Start();

                    while (true)
                    {
                        TcpClient c = listener.AcceptTcpClient();
                        ClientHandler newClient = new ClientHandler(c, this);
                        clients.Add(newClient);

                        Thread clientThread = new Thread(newClient.Run);
                        clientThread.Start();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (listener != null)
                        listener.Stop();
                }
            }
Пример #43
0
 public HTTPServer(ClientHandler del)
 {
     clientHandler = del;
 }
Пример #44
0
        private void WaitConfigRun()
        {
            while (configurator.Status != Configurator.State.done)
            {
                try
                {
                    Console.WriteLine("Waiting for game client..");
                    Socket handler = Socket.Accept();
                    Console.WriteLine("Get Handler..");
                    byte[] bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);

                    byte[] bytesPeer = new byte[1024];
                    handler.Receive(bytesPeer);

                    Message msg = new Message();
                    msg.Parse(bytesPeer);

                    PeerIDs = msg.list;

                    configurator.Parse(bytes);
                    if (configurator.IPTable.Count > 2)
                    {
                        StartConfig();
                    }
                    ClientHandler handlerClient = new ClientHandler(this, handler);
                    if (configurator.IPTable.Count > 2)
                    {
                        handlerClient.WaitConfigComplete();
                    }
                    else
                    {
                        configurator.Status = Configurator.State.done;
                    }

                    // Create Client Handler
                    lock (ClientHandlers)
                    {
                        ClientHandlers.Add(handlerClient);
                    }

                    Console.WriteLine(ClientHandlers.Count);
                }
                catch (Exception E)
                {

                }
            }
        }
Пример #45
0
		public GameUtilitiesImpl(ClientHandler client) {
			this.client = client;
		}
Пример #46
0
		public PartyServiceImpl(ClientHandler client) {
			this.client = client;
		}
Пример #47
0
 internal EngineAPI(ClientHandler client)
 {
     this.client = client;
 }
Пример #48
0
        public ClientHandler Connect(string IP)
        {
            try
            {
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = System.Net.IPAddress.Parse(IP);
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 12000);

                //Create TCP/IP socket
                Socket handler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                handler.Connect(remoteEP);

                ClientHandler clientHandler = new ClientHandler(this, handler);
                lock (ClientHandlers)
                {
                    ClientHandlers.Add(clientHandler);
                }
                return clientHandler;
            }
            catch (SocketException se)
            {
                System.Diagnostics.Debug.WriteLine(IP + "," + se.ToString());
                if (se.ErrorCode == (int)SocketError.ConnectionRefused || se.ErrorCode == (int)SocketError.TimedOut)
                {
                    return Connect(IP);
                }
                return null;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(IP + "," + e.ToString());
                return null;
            }
        }
        public InterviewerPage(bool isCont = false, string interviewerId = "")
        {
            InitializeComponent();
            IsManagerListening = false;

            interviewerId = string.IsNullOrEmpty(interviewerId) ? Guid.NewGuid().ToString() : interviewerId;
            Title         = interviewerId;

            var client = new ClientHandler("Interviewer", "SendMessageManager");

            Task.Run(async() => await client.StartAsync());
            var displayOnce = true;


            var mainStack = new StackLayout {
                Padding = new Thickness(5, 5, 5, 5)
            };

            var contentModel = new List <ContentModel>();

            if (isCont)
            {
                label.Text = "2. What beverages do you enjoy?";
                var brands = new[] { "Cola", "Fanta", "Pepsi", "7Up" };

                var categories2 = new CheckBox(brands);

                mainStack.Children.Add(label);
                mainStack.Children.Add(categories2);
                mainStack.Children.Add(button);

                categoryContent = new ContentModel {
                    Type = "CheckBox", Categories = brands
                };

                categories2.Clicked += async(sender, args) =>
                {
                    categoryContent.SelectedCategries = categories2.CategoryLabels.ToArray();

                    if (IsManagerListening)
                    {
                        await SendMessage(categoryContent, interviewerId);
                    }
                };

                button.Clicked += async(sender, e) =>
                {
                    await Navigation.PushAsync(new FinishPage(interviewerId));
                };

                Content = mainStack;

                client.Message += async(sender, e) =>
                {
                    if (e.Message == "start")
                    {
                        IsManagerListening = true;
                        if (displayOnce)
                        {
                            await SendMessage(categoryContent, interviewerId);

                            displayOnce = false;
                        }
                    }

                    if (e.Message == "stop")
                    {
                        IsManagerListening = false;
                    }
                };
            }

            if (!isCont)
            {
                label.Text = "1. Do you drink cooldrink";
                var yesNo = new[] { "Yes", "No" };

                var categories1 = new RadioButton(yesNo);

                mainStack.Children.Add(label);
                mainStack.Children.Add(categories1);
                mainStack.Children.Add(button);

                categoryContent = new ContentModel {
                    Type = "RadioButton", Categories = yesNo
                };

                categories1.Clicked += async(sender, args) =>
                {
                    categoryContent.Text = categories1.CheckedValue;
                    if (IsManagerListening)
                    {
                        await SendMessage(categoryContent, interviewerId);
                    }
                };

                button.Clicked += async(sender, e) =>
                {
                    await Navigation.PushAsync(new InterviewerPage(true, interviewerId));
                };

                Content = mainStack;

                client.Message += async(sender, e) =>
                {
                    if (e.Message == "start")
                    {
                        IsManagerListening = true;
                        if (displayOnce)
                        {
                            await SendMessage(categoryContent, interviewerId);

                            displayOnce = false;
                        }
                    }

                    if (e.Message == "stop")
                    {
                        IsManagerListening = false;
                    }
                };
            }



            //initial screen share send if manager starts up first
            Task.Run(async() =>
            {
                if (IsManagerListening)
                {
                    await SendMessage(categoryContent, interviewerId);
                }
            });
        }
    /// <summary>
    /// Adds the newly created client handler to the client handler list
    /// </summary>
    /// <param name="handler"> The client handler that was created by the server</param>
    private void AddMessageListener(ClientHandler handler)
    {
        handler.OnMessageReceived += HandleMessage;

        _clientHandlers.Add(handler);
    }
Пример #51
0
        public Stream OpenFile(ClientHandler client, ulong guid)
        {
            var data = GetHashData(guid);

            return(client.OpenCKey(data.ContentKey));
        }
 /// <summary>
 /// Responds to the HeartBeat event (does nothing at the moment, because the server is already sending too many packets
 /// </summary>
 /// <param name="handler"> The handler, that is supposed to send a HeartBeat event to its client</param>
 private void RespondToHeartBeat(ClientHandler handler)
 {
     //handler.SendPacket(new HeartBeat().Serialize(), 0);
 }
Пример #53
0
		public ToonServiceExternalImpl(ClientHandler client) {
			this.client = client;
		}
Пример #54
0
 static Demo()
 {
     Client = new ClientHandler(new HttpApiClient());
 }
 public IClientHandler getClientHandler()
 {
     ClientHandler ch = new ClientHandler();
     ch.setMessageReceivedCallback(mrc);
     return ch;
 }
Пример #56
0
    static void Main(string[] args)
    {
        int threadCount = 0;

        try
        {
            int port = 13000;
            IPAddress address = IPAddress.Parse("127.0.0.1");

            // IPAddress address = IPAddress.Parse("142.232.246.23");

            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket s = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            s.Bind(ipe);
            s.Listen(10);

            while(true)
            {
                Socket cls = s.Accept();

                threadCount++;
                ClientHandler ch = new ClientHandler(cls, threadCount);
                Thread t = new Thread(new ThreadStart(ch.Handler));
                t.Start();
            }

            s.Close();
        }
        catch (SocketException e)
        {
            Console.WriteLine("Socket exception: {0}", e);
        }

        Console.Read();
    }
Пример #57
0
 public FollowersServiceImpl(ClientHandler client)
 {
     this.client = client;
 }
        public void TestInit()
        {
            ClientHandler Handler = new ClientHandler();

            ContractCheck = new EazySDK.Utilities.ContractPostChecks();
        }
 public ChatRequest(ClientHandler requestClient, ClientHandler inviteClient, string id)
 {
     this._requestClient = requestClient;
     this._inviteClient  = inviteClient;
     this._chatID        = id;
 }
Пример #60
0
		public ExchangeServiceImpl(ClientHandler client) {
			this.client = client;
		}