コード例 #1
0
        public void Connect(string ip, int port)
        {
            AutoResetEvent ev = new AutoResetEvent(false);

            var conn = new TCPConnection();

            conn.ConnectedToServer += delegate { ev.Set(); };

            conn.Connect(ip, port);
            if (!ev.WaitOne(5000))
            {
                throw new Exception("Connection timed out!");
            }

            var cpm = new ClientPacketManagerNetworked(conn);

            conn.Receiving = true;
            Thread.Sleep(100);
            cpm.WaitForUDPConnected();
            cpm.SyncronizeRemotePacketIDs();


            var gen = new NetworkPacketFactoryCodeGenerater(TWDir.Cache.CreateChild("GodGame").CreateFile("ClientPackets" + (new Random()).Next() + ".dll").FullName);

            UserInputHandlerTransporter = cpm.CreatePacketTransporter("UserInputHandler", gen.GetFactory <UserInputHandlerPacket>(), PacketFlags.TCP);
            UserInputTransporter        = cpm.CreatePacketTransporter("UserInput", gen.GetFactory <UserInputPacket>(), PacketFlags.TCP);
            GameStateDeltaTransporter   = cpm.CreatePacketTransporter("GameStateDelta", gen.GetFactory <GameStateDeltaPacket>(), PacketFlags.TCP);

            gen.BuildFactoriesAssembly();
        }
コード例 #2
0
        // True if connected to a hub
        // false if attempted to connect to a leaf ( but has certainly retrieved many hubs )
        public bool TryConnect()
        {
            try {
                bool success = false;
                G2Log.Write("GHandshake : Try to connect to " + remote_host.ToString());
                var isConnected = tcp.Connect();
                if (!isConnected)
                {
                    return(false);
                }
                OnConnected();
                success = OnResponse();
                if (success)
                {
                    //bool connected = tcp.CheckConnection();
                    //Log.Write("GHandshake : Connected ? " + connected);
                    OnReply();
                }
                else
                {
                    tcp.Close();
                }

                return(success);
            } catch (Exception e) {
                tcp.Close();
                return(false);
            }
        }
コード例 #3
0
        public ConnectViewModel(TCPConnection connection)
        {
            this.connection = connection;
            OnConnectedChanged();
            this.connection.ConnectedChanged += (s, e) => OnConnectedChanged();
            this.connection.MessageReceived  += (s, e) => OnMessageReceived(e.ReceivedData);
            this.connection.ConnectionLost   += (s, e) => connection.Connect(Port);

            Port = 4444;
        }
コード例 #4
0
 void ConnectCommandExecute()
 {
     if (connection.IsConnected)
     {
         connection.Disconnect();
     }
     else
     {
         connection.Connect(Port);
     }
 }
コード例 #5
0
ファイル: TelnetController.cs プロジェクト: rypl/naogui
        // Connect to server and send initial responses
        public void Connect(string username, string password, string host, int port)
        {
            if (telnetClient.Connected)
            {
                throw new Exception("Already Connected");
            }

            telnetClient.Connect(host, port);

            // Things our client is requesting
            SendCommand(TelnetHelper.DO, 0x03); // DO Suppress Go Ahead

            Console.WriteLine("Connected!");
        }
コード例 #6
0
 private void sendButton_Click(object sender, EventArgs e)
 {
     try
     {
         using (var conn = TCPConnection.Connect(IPAddress.Loopback, 8080))
         {
             conn._incomingMessage += OnIncomingMessage;
             // workaround for response that has not come yet
             System.Threading.Thread.Sleep(500);
             conn.Receive();
         }
     } catch (SocketException se)
     {
         statusLabel.Text = "Error. Connection has been closed by server";
     }
 }
コード例 #7
0
ファイル: G2BrowseSearch.cs プロジェクト: nikkolasg/gnutella2
        public void StartBrowsing()
        {
            TCPConnection con = TCPConnection.getPeerConnection(Peer);

            if (!con.Connect())
            {
                G2Log.Write("G2BrowseSearch could not connect to Peer " + this.Peer.ToString());
                if (EndSearch != null)
                {
                    EndSearch(referenceToPeer, referenceToSearchResults, packetResults);
                }
                return;
            }
            if (!SendHttpRequest(con))
            {
                if (EndSearch != null)
                {
                    EndSearch(referenceToPeer, referenceToSearchResults, packetResults);
                }
                Peer.Close();
                return;
            }

            bool streaming = ReadResponseHeader(con);

            if (!streaming)
            {
                if (EndSearch != null)
                {
                    EndSearch(referenceToPeer, referenceToSearchResults, packetResults);
                }
                Peer.Close();
                return;
            }

            // start to  read the flow of packets
            this.Peer.connection = new HubSocket(this.Peer, con.sock, reader);
            this.Peer.connection.Start();


            G2Log.Write("G2BrowseSearch : browsing peer " + Peer.ToString() + " ...");
            SearchTimer           = new Timer(Settings.WAIT_TIME_BROWSING_MS);
            SearchTimer.Elapsed  += new ElapsedEventHandler(SearchTimeOut);
            SearchTimer.AutoReset = false;

            SearchTimer.Start();
        }
コード例 #8
0
 public void Connect(string ip, int port)
 {
     TCPConnection.Connect(ip, port);
 }
コード例 #9
0
ファイル: Client.cs プロジェクト: filscorporation/Match
 public void ConnectToServer()
 {
     ClientTCP.Connect(IP, Port);
 }
コード例 #10
0
 private void connectButton_Click(object sender, RoutedEventArgs e)
 {
     networkListBox.Items.Add("Connecting...");
     myCon.Connect("localhost", updateNetworkListBox);
 }
コード例 #11
0
        private async void Login(bool fromRegister) {
            if (connecting) // only allow one connection at once
                return;
            connecting = true;

            if (!ValidateUsername(username)) { // only allow valid usernames to login
                connecting = false;
                return;
            }
            if (fromRegister) // this login call was from a register
                offlineScreen.UpdateStatusText(" Logging in...");
            else
                offlineScreen.UpdateStatusText("Logging in...");
            offlineScreen.ShowResume(false);
            string postData = string.Format(postDataFormat, username, password);

            HTTPConnectionResult loginResult = await httpConn.GetPostResult(urlLogin, postData);
            if (!loginResult.error) { // not an error connecting to server
                LoginResponse response = new LoginResponse(loginResult.message);
                offlineScreen.UpdateStatusText(response.message);

                if (response.success) { // login was sucessful
                    // save the username and password in local settings so that it can load it later
                    PermanentStorage.Set("username", username);
                    PermanentStorage.Set("password", password);

                    // Initialize data structures and store in CoreApplication.Properties for the following:
                    /**
                     * Friends list
                     * Party list
                     * News
                     * Money
                     **/
                    // TODO: Retrieve and parse friend list data from HTTP response
                    // TODO: Retrieve and parse news information from HTTP response
                    // TODO: Retrieve money from SQLite

                    Storage.Set("news", response.news);
                    Storage.Set("unlocked", response.unlockedProfiles);

                    PlayerData mydata = new PlayerData(response.username, response.profile, response.lvl, 0);
                    mydata.rank = response.rank;
                    mydata.money = 2000;
                    Storage.Set("myPlayerData", mydata);

                    // set the upgrades
                    foreach (string s in response.gameUpgrades.Keys) {
                        GameData gd = GameConstants.GetGameData(s);
                        int[] upgrades = response.gameUpgrades[s];
                        gd.GameUpgrades[0].Level = upgrades[0];
                        gd.GameUpgrades[1].Level = upgrades[1];
                        gd.GameUpgrades[2].Level = upgrades[2];
                    }
                    StoreData.GameUpgradePrices = response.gameUpgradePrices.ToArray();

                    // Create a TCP connection
                    ITCPConnection conn = new TCPConnection();
                    conn.pMessageReceivedEvent += delegate(string m, bool error, ITCPConnection connection) {
                        JObject o = JObject.Parse(m);
                        // TODO: Base TCP handler handles the following
                        /**
                         * Friend list updates
                         * Party updates
                         * Store transactions
                         **/
                        if (o["conn_id"] != null) {
                            // authorize the connection using auth key recieved from http login
                            conn.SendMessage("{\"auth\": \"" + response.auth + "\"}");
                            Storage.Set("TCPSocket", conn);

                            // navigate to gamepage to start the game
                            Storage.Set("username", response.username);
                            offlineScreen.ShowControls(false);
                            offlineScreen.GoToNextScreen(typeof(HomeScreen));
                        }
                    };
                    conn.pConnectionClosedEvent += TCPConnectionClosed;
                    if (!conn.Connect()) {
                        System.Diagnostics.Debug.WriteLine("Error connecting to TCP server");
                        offlineScreen.UpdateStatusText("Error connecting to server. Please try again.");
                    }
                } else { // could not log in with the creditions. invalid username and password
                    PermanentStorage.Remove("username"); // remove any stored username and passwords
                    PermanentStorage.Remove("password");
                    ResetScreen(response.message); // reset the screen
                }

            } else {
                // there was an error when connecting to the http server
                System.Diagnostics.Debug.WriteLine("Error connecting to http server");
                offlineScreen.UpdateStatusText("Error connecting to server. Please try again.");
                if (savedInfo) { // logged in from saved information
                    offlineScreen.ShowResume(true); // show the resume button
                } else {
                    offlineScreen.ShowUserInput(true); 
                }
            }

            connecting = false;
        }
コード例 #12
0
 public void Connect(TcpClient client)
 {
     TCPConnection.Connect(client);
 }
コード例 #13
0
ファイル: Connect.cs プロジェクト: TobiH-GE/Network
 public void Execute(object parameter)
 {
     TCPConnection.Username = Parent.Username;
     TCPConnection.Connect(Parent.Address, Parent.Port);
     Parent.IsConnected = true;
 }
コード例 #14
0
        public void TestTCPConnect()
        {
            bool           success  = false;
            AutoResetEvent testDone = new AutoResetEvent(false);

            TCPConnectionListener listener = new TCPConnectionListener(5013);

            listener.Listening = true;
            TCPConnection client1 = null;

            listener.ClientConnected +=
                delegate(object sender, TCPConnectionListener.ClientConnectedEventArgs e)
            {
                Console.WriteLine("Client connected to server!");
                TCPConnection serverClient1 = new TCPConnection(e.CL);
                serverClient1.SendPacket(new byte[] { 1, 2, 3, 4 }, TCPPacketBuilder.TCPPacketFlags.None);
                serverClient1.Receiving = true;


                serverClient1.PacketRecievedAsync +=
                    delegate(object sender2, BaseConnection.PacketRecievedEventArgs e2)
                {
                    for (int i = 1; i < 4 + 1; i++)
                    {
                        if (e2.Dgram[i - 1] != i)
                        {
                            success = false;         // optional
                            testDone.Set();
                            return;
                        }
                    }
                    Console.WriteLine("Packet received from client!");

                    success = true;
                    testDone.Set();
                };
            };


            client1 = new TCPConnection();

            client1.ConnectedToServer +=
                delegate(object sender, TCPConnection.ConnectedToServerEventArgs e)
            {
                Console.WriteLine("Connected successfully!");
                client1.Receiving = true;
            };

            client1.ConnectError +=
                delegate(object sender, TCPConnection.ConnectErrorEventArgs e)
            {
                throw e.Ex;
            };

            client1.PacketRecievedAsync +=
                delegate(object sender, BaseConnection.PacketRecievedEventArgs e)
            {
                for (int i = 1; i < 4 + 1; i++)
                {
                    if (e.Dgram[i - 1] != i)
                    {
                        success = false;     // optional
                        testDone.Set();
                        return;
                    }
                }
                Console.WriteLine("Packet received from server!");
                client1.SendPacket(new byte[] { 1, 2, 3, 4 }, TCPPacketBuilder.TCPPacketFlags.None);
            };



            client1.Connect(System.Net.IPAddress.Parse("127.0.0.1"), 5013);

            //testDone.WaitOne(5000);
            testDone.WaitOne();

            Assert.True(success);
        }