Esempio n. 1
1
        public override void InputThread()
        {
            try
            {
                using (Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    mainSocket.Bind(new IPEndPoint(IPAddress.Any, this.Port));
                    mainSocket.Listen(10);
                    logger.Info("TCP listening on port: {0}", this.Port);

                    byte[] buffer = new byte[65536];

                    while (!InputThreadQuitRequested())
                    {
                        if (mainSocket.Poll(1000000, SelectMode.SelectRead))
                        {
                            Socket childSocket = mainSocket.Accept();
                            TCPConnection conn = new TCPConnection(this, childSocket);
                            logger.Info("{0} accepted.", conn);
                            conn.Start();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                RaiseError(ex);
            }
            finally
            {
            }
        }
Esempio n. 2
0
 void Awake()
 {
     //add a copy of TCPConnection to this game object
     myTCP = gameObject.AddComponent<TCPConnection>();
     sgen = gameObject.GetComponent<SubGenerator> ();
     Debug.Log("Attempting to connect..");
     myTCP.setupSocket();
 }
Esempio n. 3
0
        private void device_PcapOnPacketArrival(object sender, Packet packet)
        {
            if (!(packet is TCPPacket)) return;

            TCPPacket tcpPacket = (TCPPacket)packet;
            // Creates a key for the dictionary
            TCPConnection c = new TCPConnection(tcpPacket);

            // Todo: gescheiter Filter
            if (!(c.DestinationPort == port || c.SourcePort == port))
                return;

            // create a new entry if the key does not exists
            if (!sharpPcapDict.ContainsKey(c) && !this.gotLock)
            {
                TcpRecon.TcpRecon tcpRecon = new TcpRecon.TcpRecon(this.serverStr, this.clientStr);
                sharpPcapDict.Add(c, tcpRecon);
                this.gotLock = true;
            }

            // Use the TcpRecon class to reconstruct the session
            if (this.sharpPcapDict.ContainsKey(c))
            {
                sharpPcapDict[c].ReassemblePacket(tcpPacket);
            }

            L2Packet l2packet = null;

             while (this.clientStr.MorePackets())
            {
                l2packet = this.gameSniffer.handlePacket(this.clientStr.ReadPacket(), false);
                if (l2packet != null)
                {
                    this.packetContainer.AddPacket(l2packet);
                    l2packet.PacketNo = this.count++;
                }
            }
            while (this.serverStr.MorePackets())
            {
                l2packet = this.gameSniffer.handlePacket(this.serverStr.ReadPacket(), true);
                if (l2packet != null)
                {
                    this.packetContainer.AddPacket(l2packet);
                    l2packet.PacketNo = this.count++;
                }
            }
        }
Esempio n. 4
0
        public TcpClient(IPv4Address dest, UInt16 port)
        {
            IPv4Address source = TCPIPStack.FindNetwork(dest);

            if (source == null)
            {
                throw new ArgumentException("Destination host unreachable", "dest");
            }

            this.connection        = new TCPConnection(dest, port, source, NextLocalPort++, 0x5656, TCPConnection.State.SYN_SENT);
            this.connection.client = this;

            TCPIPStack.tcpSockets.Add(connection);

            TCPPacket packet = new TCPPacket(connection, connection.LocalSequenceNumber, 0, 0x02, 8192);

            TCPIP.IPv4OutgoingBuffer.AddPacket(packet);
        }
Esempio n. 5
0
    private async void Communicate(TCPConnection connection)
    {
        while (connection.active)
        {
            List <byte> data = await connection.Receive();

            if (data.Count > 0)
            {
                string channel = data.ReadString();
                if (channel == "disconnection")
                {
                    connection.active = false;
                }
                else
                {
                    //received a message from the host!
                    onMessageReception.Invoke(connection, channel, data);
                }
            }
            else
            {
                Haze.Logger.LogWarning("Received data with length == 0 from connection " + connection);
                connection.active = false;
            }
        }

        //Attempt to send a "disconnection" message before closing
        {
            List <byte> data = new List <byte>();
            data.WriteString("disconnection");
            try {
                await connection.Send(data);
            } catch (Exception e) {
                //nevermind.
            }
        }

        onConnectionEnd.Invoke(connection);
        users.Remove(connection);
        if (!connection.UDP)
        {
            connection.client.Close();
        }
    }
Esempio n. 6
0
        /// <summary>
        /// you can also send objects, here we create a xxx, i mean we send a xxx by tcp and then the client creates it after deserializing and other stuff
        /// </summary>
        public void SendMyObject()
        {
            ElbowCylindrical   elbowCylindrical = new ElbowCylindrical(1, "ElbowCylindrical", "Element", 1, 1, new Length(0.01, LengthUnit.Meter), new Length(0.1, LengthUnit.Meter), new Angle(90, AngleUnit.Degree), new Length(0, LengthUnit.Meter), false, new Length(0, LengthUnit.Meter), new Length(0.4, LengthUnit.Meter), new Length(0, LengthUnit.Meter), new Angle(0, AngleUnit.Degree), new Angle(0, AngleUnit.Degree));
            Caps               caps             = new Caps(1, "Caps", "Element", 1, 1, "Caps", new Length(0.2, LengthUnit.Meter), new Length(0.5, LengthUnit.Meter), new Length(0.4999, LengthUnit.Meter), new Length(0.5, LengthUnit.Meter), new Length(1, LengthUnit.Meter), new Length(0, LengthUnit.Meter), new Pressure(0, PressureUnit.Bar), "Caps", false);
            PipeRectangular    pipeRectangular  = new PipeRectangular(1, "PipeRectangular", "Element", 1, 1, "PipeRectangular", "Shape", new Length(0.1, LengthUnit.Meter), new Length(1, LengthUnit.Meter), new Length(0.5, LengthUnit.Meter), new Length(0.5, LengthUnit.Meter));
            Cone               cone             = new Cone(1, "Tube", "Element", 1, 1, new Length(0.1, LengthUnit.Meter), new Length(2, LengthUnit.Meter), new Length(1, LengthUnit.Meter), new Length(2, LengthUnit.Meter), new Angle(0, AngleUnit.Degree), new Length(0, LengthUnit.Meter), new Length(0, LengthUnit.Meter), new Length(0, LengthUnit.Meter), new Length(0, LengthUnit.Meter));
            Tube               tube             = new Tube(1, "Tube", "Element", 1, 1, "tube", new Length(1, LengthUnit.Meter), new Length(0.1, LengthUnit.Meter), new Length(2, LengthUnit.Meter));
            List <BaseElement> objectsList      = new List <BaseElement> {
                elbowCylindrical, caps, pipeRectangular, cone, tube
            };

            index = index >= objectsList.Count - 1 ? index = 0 : index + 1;
            BaseElement c = objectsList[index];

            JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Auto,
                Formatting       = Formatting.Indented
            };

            _jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter());
            string json = JsonConvert.SerializeObject(c, typeof(BaseElement), _jsonSerializerSettings);

            CommunicateElement messageObject = new CommunicateElement(NetworkComms.NetworkIdentifier, json, c.Designation);

            //Print out the IPs and ports we are now listening on
            Console.WriteLine();
            Console.WriteLine("[Object] Server messaging these TCP connections:");

            foreach (IPEndPoint localEndPoint in connectedClients)
            {
                Console.WriteLine($"{localEndPoint.Address}:{localEndPoint.Port}");
                try
                {
                    TCPConnection.GetConnection(new ConnectionInfo(localEndPoint), customSendReceiveOptions).SendObject("Element", messageObject);
                }
                catch (CommunicationException) { Console.WriteLine("CommunicationException"); }
                catch (ConnectionShutdownException) { Console.WriteLine("ConnectionShutdownException"); }
                catch (Exception) { Console.WriteLine("Autre exception"); }
            }

            Console.WriteLine("Server stops messaging");
            Console.WriteLine();
        }
Esempio n. 7
0
        public bool TryToConnect()
        {
            try
            {
                if (IsConnected)
                {
                    return(true);
                }
                TCPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 8181), true);
                return(IsConnected);
            }
            catch (Exception ex)
            {
#if !STANDALONE
                vaProxy.WriteToLog(ex.ToString(), "red");
#endif
                return(false);
            }
        }
Esempio n. 8
0
    protected override void ThreadFunction()
    {
        try
        {
            TCPConnection conn = TCPConnection.GetConnection(connectionInfo);
            if (isPingOnly)
            {
                command = new VRCommand(Enums.ControlMessage.NONE);
            }

            conn.SendObject("Command", command);

            //Debug.Log("Connected!");
        }
        catch (Exception ex)
        {
            Debug.Log("Connection Error! " + ex.ToString());
        }
    }
Esempio n. 9
0
        private void Initialize()
        {
            // 保存传入的应用程序名称
         
            // 设置标题
            this.Text = "微风IM V3";

            //从配置文件中获取IP
            IPAddress = System.Configuration.ConfigurationManager.AppSettings["IPAddress"];

            //从配置文件中获取端口
            Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"]);

            connInfo = new ConnectionInfo(IPAddress, Port);

            newTcpConnection = TCPConnection.GetConnection(connInfo);

            Common.TcpConn = newTcpConnection;
        }
Esempio n. 10
0
        // generic method to send command object to server
        private Task SendCommandToServer(VRCommand cmdObj)
        {
            return(Task.Run(() =>
            {
                try
                {
                    cmdObj.MachineName = System.Environment.MachineName;
                    cmdObj.LiveClientStatus = _internalCurrentClientStatus;
                    cmdObj.AdditionalInfo = _internalAdditionalInfo;
                    TCPConnection conn = TCPConnection.GetConnection(_targetServerConnectionInfo);

                    conn.SendObject("Command", cmdObj);
                }
                catch (Exception ex)
                {
                    logger.Info("SendCommandToServer" + ex.ToString());
                }
            }));
        }
Esempio n. 11
0
        public void Start()
        {
            if (Status == TrackerStatus.Stopped)
            {
                try
                {
                    TCPConnection.StartListening(CommonHelpers.GetLocalEndPoint(CommonHelpers.TrackerPort), false);
                    Status = TrackerStatus.Started;
                }
                catch
                {
                    NetworkComms.Logger.Error("Can't start listener on this IP: " + CommonHelpers.GetLocalEndPoint(CommonHelpers.TrackerPort).ToString());
                }

                NetworkComms.Logger.Warn("===== Tracker started =====");

                t.Start();
            }
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            try
            {
                string serverIP;
                string input;
                int    serverPort;

                System.Console.WriteLine("Please enter the server IP and press return.");
                input    = System.Console.ReadLine();
                serverIP = input;

                //serverIP = "127.0.0.1";
                System.Console.WriteLine("Please enter the port and press return.");
                input      = System.Console.ReadLine();
                serverPort = int.Parse(input);
                //serverPort = 8000;
                System.Console.WriteLine("Connection to {0}:{1}...", serverIP, serverPort);


                ConnectionInfo server = new ConnectionInfo(serverIP, serverPort);
                Connection     conn   = TCPConnection.GetConnection(server, customSendReceiveOptions);

                conn.AppendIncomingPacketHandler <Message>("CardGame", HandleGame, customSendReceiveOptions);
                conn.AppendIncomingPacketHandler <string>("Chat", HandleChat, customSendReceiveOptions);

                game.Run(conn);
                //conn.SendObject("CardGame", message);
                //NetworkComms.SendObject("CardGame", serverIP, serverPort, message);
                //System.Console.WriteLine("Message sent " + message.Id);
                //if (message.Id != Message.Step.ERROR)
                //    message.Id += 1;
                //System.Console.WriteLine("Press q to quit or any other key to send another message.");
                //if (System.Console.ReadKey(true).Key == System.ConsoleKey.Q)
                //    state = false;

                NetworkComms.Shutdown();
            }
            catch (System.Exception error)
            {
                System.Console.Error.WriteLine(error.GetBaseException());
            }
        }
Esempio n. 13
0
        public void SendMessage(string numValue, string strValue)
        {
            //If we have tried to send a zero length string we just return
            if (strValue.Trim() == "" && numValue.Trim() == "")
            {
                return;
            }

            //We may or may not have entered some server connection information
            ConnectionInfo serverConnectionInfo = null;

            if (ServerIPAddress != "")
            {
                try { serverConnectionInfo = new ConnectionInfo(ServerIPAddress, ServerPort); }
                catch (Exception)
                {
                    ShowMessage("Failed to parse the server IP and port. Please ensure it is correct and try again");
                    return;
                }
            }
            // Check if input value is number
            int value = 0;

            int.TryParse(numValue, out value);
            //We wrap everything we want to send in the ChatMessage class we created
            DataSendModel message = new DataSendModel(NetworkComms.NetworkIdentifier, LocalName, value, strValue);

            //We write our own message to the chatBox
            //AppendLineToChatHistory(message.SourceName + " - " + message.Message);

            //If we provided server information we send to the server first
            if (serverConnectionInfo != null)
            {
                //We perform the send within a try catch to ensure the application continues to run if there is a problem.
                try
                {
                    TCPConnection.GetConnection(serverConnectionInfo).SendObject("ClientMessage", message);
                }
                catch (CommsException) { }
                catch (Exception) { }
            }
            return;
        }
Esempio n. 14
0
        private void OnSend(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(MessageTextView.Text))
            {
                var message = MessageTextView.Text;

                try
                {
                    foreach (var node in Nodes)
                    {
                        try
                        {
                            var connection = TCPConnection.GetConnection(new ConnectionInfo(node.Key, 49999));
                            connection.SendObject("Chat", message);
                        }
                        catch (DuplicateConnectionException)
                        {
                            // todo: establishing connection simultaneously
                        }
                        catch (ConnectionSetupException)
                        {
                            node.Value.Broken = true;
                        }
                    }

                    var brokenNodes = Nodes.Where(n => n.Value.Broken);
                    foreach (var node in brokenNodes)
                    {
                        if (Nodes.TryRemove(node.Key, out Node removedNode))
                        {
                            RunOnUiThread(() => Messages.Add($"Disconnected node: {removedNode.Name}"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Messages.Add(ex.Message);
                }

                MessageTextView.Text = string.Empty;
            }
        }
        /// <summary>
        /// Gets a dictionary that maps a list of connections to a PID
        /// </summary>
        /// <returns>The dictionary that maps conenctions to PIDS</returns>
        private Dictionary <uint, List <TCPConnection> > GetPidToConnectionsDictionary()
        {
            Dictionary <uint, List <TCPConnection> > pidToConnections = new Dictionary <uint, List <TCPConnection> >();

            try
            {
                IPHelperExtendedTCPTableWrapper iphw = new IPHelperExtendedTCPTableWrapper();
                List <MIB_TCPROW_OWNER_PID>     cns  = iphw.GetAllTCPv4Connections();

                foreach (MIB_TCPROW_OWNER_PID cn in cns)
                {
                    TCPConnection con = new TCPConnection();

                    Array.Reverse(cn.localPort);
                    Array.Reverse(cn.remotePort);

                    byte[] la = BitConverter.GetBytes(cn.localAddr);
                    byte[] ra = BitConverter.GetBytes(cn.remoteAddr);

                    con.LocalIP = Convert.ToInt32(la[0]) + "." + Convert.ToUInt32(la[1]) + "" +
                                  "." + Convert.ToUInt32(la[2]) + "." + Convert.ToUInt32(la[3]);

                    con.RemoteIP = Convert.ToInt32(ra[0]) + "." + Convert.ToUInt32(ra[1]) + "" +
                                   "." + Convert.ToUInt32(ra[2]) + "." + Convert.ToUInt32(ra[3]);

                    con.State      = (TCPConnectionState)cn.state;
                    con.LocalPort  = BitConverter.ToUInt16(cn.localPort, 2);
                    con.RemotePort = BitConverter.ToUInt16(cn.remotePort, 2);
                    if (!pidToConnections.ContainsKey(cn.owningPid))
                    {
                        pidToConnections.Add(cn.owningPid, new List <TCPConnection>());
                    }

                    pidToConnections[cn.owningPid].Add(con);
                }
            } catch (Exception exc)
            {
                MyDebugger.Instance.LogMessage(exc, DebugVerbocity.Exception);
            }

            return(pidToConnections);
        }
 public void OnReceiveGuideUnpair(TCPConnection connection)
 {
     if (currentlyPaired != null && connection == currentlyPaired)
     {
         currentlyPaired   = null;
         connection.paired = false;
         Haze.Logger.Log("Unpaired.");
         onUnpair.Invoke();
         SendPairConfirm();
     }
     else if (currentlyPaired != null)
     {
         Haze.Logger.LogWarning("Received Unpair message from a guide we're not paired to. Accepting request regardless.");
         OnReceiveGuideUnpair(currentlyPaired);            //simulate receiving it from our paired guide instead
     }
     else
     {
         Haze.Logger.LogWarning("Cannot unpair.");
     }
 }
Esempio n. 17
0
 public void Close()
 {
     if (closed)
     {
         return;
     }
     // we haven't done a handshake or it is a leaf
     if (connection == null)
     {
         TCPConnection.CloseConnection(this);
     }
     else
     {
         connection.Close();
     }
     this.Buffer.Clear();
     this.SearchTimer.Stop();
     this.PingTimer.Stop();
     this.closed = true;
 }
Esempio n. 18
0
            /// <summary>
            /// Send a message to clients
            /// </summary>
            private void SendMessage()
            {
                if (messageText.Text.Trim() == "")
                {
                    return;
                }
                Message messageToSend = new Message(NetworkComms.NetworkIdentifier, localName.Text, "", messageText.Text, messageSendIndex++);

                lock (lastPeerMessageDict) lastPeerMessageDict[NetworkComms.NetworkIdentifier] = messageToSend;
                AppendLineToRichChatBox("[" + (DateTime.Now).ToString(hourFormat) + "] " + messageToSend.SourceName + " : " + messageToSend.MessageContent);
                RefreshMessagesFromBox();
                this.messageText.Text = "";
                var otherConnectionInfos = (from current in NetworkComms.AllConnectionInfo() select current).ToArray();

                foreach (ConnectionInfo info in otherConnectionInfos)
                {
                    try { TCPConnection.GetConnection(info).SendObject("Message", messageToSend); }
                    catch (CommsException) { MessageBox.Show("A CommsException occurred while trying to send message to " + info, "CommsException", MessageBoxButton.OK); }
                }
            }
Esempio n. 19
0
            /// <summary>
            /// click handler to disconnect from server
            /// </summary>
            private void DisconnectButton_Click(object sender, RoutedEventArgs e)
            {
                Connection co = TCPConnection.GetConnection(serverConnectionInfo);

                co.CloseConnection(true);

                sendMessageButton.IsEnabled = false;
                messageText.IsEnabled       = false;
                playerButton.IsEnabled      = false;
                aiButton.IsEnabled          = false;
                playersListButton.IsEnabled = false;
                putButton.IsEnabled         = false;
                richChatBox.IsReadOnly      = true;
                disconnectButton.IsEnabled  = false;
                connectButton.IsEnabled     = true;
                serverIP.IsEnabled          = true;
                serverPort.IsEnabled        = true;
                localName.IsEnabled         = true;
                inventoryButton.IsEnabled   = false;
            }
Esempio n. 20
0
        private void StartNetworkListener()
        {
            Log.Info("Starting TCP Listener");
            try
            {
                string ip = Common.LocalIPAddress();
                NetworkComms.AppendGlobalIncomingPacketHandler <string>("Plugin", PluginMessageReceived);
                NetworkComms.AppendGlobalIncomingPacketHandler <string>("Method", MethodMessageReceived);
                //Start listening for incoming connections
                TCPConnection.StartListening(new IPEndPoint(IPAddress.Parse(ip), 10051));
                //TCPConnection.StartListening(true);

                foreach (System.Net.IPEndPoint localEndPoint in TCPConnection.ExistingLocalListenEndPoints())
                {
                    Log.Info("Service listening for TCP connection on: " + localEndPoint.Address + ":" + localEndPoint.Port);
                }
            }
            catch (Exception ex)
            { Log.Error("Error starting TCP Listener: " + ex.Message, ex); }
        }
Esempio n. 21
0
 public void OnReceiveChoiceConfirmation(TCPConnection connection, int choiceIndex)
 {
     //choice index is either 0 or 1
     if (currentVideo != null && currentVideo.Settings.choices.Length > 0)
     {
         string       nextVideo        = choiceIndex == 0 ? currentVideo.Settings.choices[0].video1 : currentVideo.Settings.choices[0].video2;
         VideoDisplay nextVideoDisplay = VideosDisplayer.Instance.FindVideo(nextVideo);
         if (nextVideoDisplay != null && nextVideoDisplay.Available)
         {
             playImmediately = true;
             LoadVideo(nextVideoDisplay);
         }
         else
         {
             Haze.Logger.LogError("Doesn't have video: " + nextVideo);
             onNextVideoIsUnavailable.Invoke();
             Stop();
         }
     }
 }
Esempio n. 22
0
            /// <summary>
            /// click handler to connect to a specific server
            /// </summary>
            private void ConnectToServer_Click(object sender, RoutedEventArgs e)
            {
                if (serverIP.Text != "")
                {
                    try
                    {
                        serverConnectionInfo = new ConnectionInfo(serverIP.Text.Trim(), int.Parse(serverPort.Text));
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Failed to parse the server IP and port. Please ensure it is correct and try again", "Server IP & Port Parse Error", MessageBoxButton.OK);
                        return;
                    }
                }

                Message messageToSend = new Message(NetworkComms.NetworkIdentifier, localName.Text, "CONNECT", "", messageSendIndex++);

                if (serverConnectionInfo != null)
                {
                    try
                    {
                        TCPConnection.GetConnection(serverConnectionInfo).SendObject("Message", messageToSend);
                    }
                    catch (CommsException)
                    {
                        MessageBox.Show("A CommsException occurred while trying to send message to " + serverConnectionInfo, "CommsException", MessageBoxButton.OK);
                        return;
                    }
                    messageText.IsEnabled       = true;
                    sendMessageButton.IsEnabled = true;
                    playerButton.IsEnabled      = true;
                    aiButton.IsEnabled          = true;
                    playersListButton.IsEnabled = true;
                    connectButton.IsEnabled     = false;
                    disconnectButton.IsEnabled  = true;
                    serverIP.IsEnabled          = false;
                    serverPort.IsEnabled        = false;
                    username            = localName.Text;
                    localName.IsEnabled = false;
                }
            }
 public void OnReceiveLoadVideoResponse(TCPConnection connection, bool ok, string errorMessage)
 {
     if (ok)
     {
         Haze.Logger.Log(connection + " has successfully loaded video.");
         ConnectionsDisplayer.DisplayedConnectionHandle handle = null;
         if (ConnectionsDisplayer.Instance)
         {
             handle = ConnectionsDisplayer.Instance.GetConnectionHandle(connection);
             if (handle != null)
             {
                 handle.display.IsVideoReady = true;
             }
         }
     }
     else
     {
         Haze.Logger.LogWarning("Error: " + connection + " could not load video: " + errorMessage);
         //TODO: display error message
     }
 }
Esempio n. 24
0
        public bool ReConnect()
        {
            bool connected = false;

            try
            {
                if (Connectable(ipAddress.ToString()))
                {
                    connectionInfo = new ConnectionInfo(ipAddress.ToString(), port);
                    TCPConnection.GetConnection(connectionInfo).EstablishConnection();

                    connected = true;
                }
            }
            catch
            {
                // Just here to avoid potential crash
            }

            return(connected);
        }
Esempio n. 25
0
        public void ConnectToServer()
        {
            serverConnectionInfo = new ConnectionInfo(endPoint, ApplicationLayerProtocolStatus.Enabled);
            int attempts = 0;

            Console.WriteLine("Connecting to server...");
            while (serverConnection == null)
            {
                try
                {
                    serverConnection = TCPConnection.GetConnection(serverConnectionInfo);
                    Console.WriteLine("Connected to server");
                    break;
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to connect, attempts: {0}", attempts);
                    attempts++;
                }
            }
        }
Esempio n. 26
0
        protected void ReceivePostAddGroupToApp(PacketHeader header, Connection connection, GroupRequest request)
        {
            // ########################################################################
            // This method requires authentication.
            // If user is not authorized then send UnAuthorized and end method.
            if (!Authorized(connection))
            {
                TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(
                    PacketName.ReUnauthorized.ToString(), 1);

                return;
            }
            // ########################################################################

            if (Administrator(connection))
            {
                groupRepository.AddAppAccess(request.accountId, request.groupId);
                TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(
                    PacketName.ReUpdateAccountInformation.ToString(), GenericResponse.Success);
            }
        }
 /// <summary>
 /// When this class is instantiated, it connects to an existing server - if one is available - or spawns
 /// a new server and connects to it
 /// </summary>
 public CollabProxyClient()
 {
     if (IsCachedServerAvailable())
     {
         try
         {
             TcpConnection = ConnectUsingCache();
         }
         catch (ConnectionSetupException)
         {
             SpawnServer();
             TcpConnection = ConnectUsingCache();
         }
     }
     else
     {
         SpawnServer();
         TcpConnection = ConnectUsingCache();
     }
     AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
 }
Esempio n. 28
0
        protected void ReceiveServiceCommand(PacketHeader header, Connection connection, ServiceCommand command)
        {
            // ########################################################################
            // This method requires authentication.
            // If user is not authorized then send UnAuthorized and end method.
            if (!accountManager.Authorized(connection))
            {
                TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(
                    PacketName.ReUnauthorized.ToString(), 1);

                return;
            }
            // ########################################################################

            string result = serviceManager.ExecuteServiceCommand(command.serviceId, command.value);

            ServiceCommand commandResult = new ServiceCommand(command.serviceId, result);

            TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(
                Networking.Data.PacketName.ReServiceResponse.ToString(), commandResult);
        }
Esempio n. 29
0
        public void start()
        {
            try
            {
                TCPconn = TCPConnection.GetConnection(new ConnectionInfo(IP, Port));
            }
            catch
            {
                Console.WriteLine("Invalid Connection Information.");
                getInfo();
                start();
                return;
            }
            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, dataProcessors, dataProcessorOptions);
            TCPconn.AppendShutdownHandler(disconnect);

            Console.WriteLine("Write 'quit' to quit | Write 'help' to get available commands");
            while (true)
            {
                string line = Console.ReadLine().ToLower();
                if (line == "quit")
                {
                    break;
                }
                switch (line)
                {
                case "help":
                    printhelp(Status.Menu);
                    break;

                case "bj":
                    BlackJack();
                    break;

                case "bt":
                    Bataille();
                    break;
                }
            }
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            SendReceiveOptions options = new SendReceiveOptions <ProtobufSerializer>();
            ConnectionInfo     conn    = new ConnectionInfo("127.0.0.1", 7777);
            TCPConnection      socket  = TCPConnection.GetConnection(conn, options);

            //response = socket.SendReceiveObject<string>("RequestLogin", "Response", int.MaxValue);
            socket.SendObject("RequestLogin");

            NetworkComms.AppendGlobalIncomingPacketHandler <int>("RequestLoginData", (packetHeader, connection, input) =>
            {
                /*Console.WriteLine("Please enter your username: "******"Please enter your password: "******"domis045", "admin");

                connection.SendObject("LoginData", cred);

                /* connection.SendObject("LoginData", "No");
                 * Console.WriteLine(connection);
                 * //connection.Dispose();*/
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <int>("DisconnectMessage", (packetHeader, connection, input) =>
            {
                Console.WriteLine("Your connection has been dropped by the server!");
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <int>("ConnectionMessage", (packetHeader, connection, input) =>
            {
                Console.WriteLine("You have connected sucesfully!");
            });

            Console.ReadLine();

            // Credentials _cred = connection.SendReceiveObject<Credentials>("RequestLoginData", "LoginData", int.MaxValue);
        }
Esempio n. 31
0
        public Commander(String targetIP, int targetPort, bool transportIsUDP)
        {
            this.transportIsUDP = transportIsUDP;

            //Init messages
            this.messages = new String[5];
            this.messages[0] = "s";
            this.messages[1] = "a";
            this.messages[2] = "r";
            this.messages[3] = "g";
            this.messages[4] = "d";

            //Create communication client
            if (transportIsUDP)
            {
                this.UDPmessager = new UDPmessager(targetIP, targetPort);
            }
            else
            {
                this.TCPClient = new TCPConnection(targetIP, targetPort);
            }
        }
Esempio n. 32
0
        protected void ReceiveUserInformationUpdateRequest(PacketHeader header, Connection connection, Account request)
        {
            // ########################################################################
            // This method requires authentication.
            // If user is not authorized then send UnAuthorized and end method.
            if (!Authorized(connection))
            {
                TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(
                    PacketName.ReUnauthorized.ToString(), 1);

                return;
            }
            // ########################################################################

            if (Administrator(connection))
            {
                accountRepository.Update(request.id, request.username, request.firstname, request.lastname);

                TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(
                    PacketName.ReUpdateAccountInformation.ToString(), GenericResponse.Success);
            }
        }
Esempio n. 33
0
        protected void ReceivePostDisableApp(PacketHeader header, Connection connection, long appId)
        {
            // ########################################################################
            // This method requires authentication.
            // If user is not authorized then send UnAuthorized and end method.
            if (!accountManager.Authorized(connection))
            {
                TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(
                    PacketName.ReUnauthorized.ToString(), 1);

                return;
            }
            // ########################################################################

            if (accountManager.Administrator(connection))
            {
                moduleRepository.DisableService(appId);

                TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(
                    PacketName.ReUpdateAccountInformation.ToString(), GenericResponse.Success);
            }
        }
Esempio n. 34
0
        private void ListenerOnConnectionReceived(StreamSocketListener sender,
                                                  StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                if (args.Socket == null)
                {
                    return;
                }
                var peerSocket = args.Socket;
                var uri        = new Uri("tcp://" + peerSocket.Information.RemoteHostName.RawName + ':' +
                                         peerSocket.Information.RemoteServiceName);
                var         peer       = new Peer("", uri, EncryptionTypes.All);
                IConnection connection = new TCPConnection(peerSocket, true);


                RaiseConnectionReceived(peer, connection, null);
            }
            catch
            {
            }
        }
            // Accept connection from specific IP address
            public bool AcceptConnection(string remoteIP)
            {
                if (!(this.isHost))
                    this.listener.Start();

                if (this.connectionList.Count < 4 && this.listener.Pending())
                {
                    TcpClient client = this.listener.AcceptTcpClient();
                    IPEndPoint endPoint = client.Client.LocalEndPoint as IPEndPoint;

                    if (endPoint != null && endPoint.Address.Equals(IPAddress.Parse(remoteIP)))
                    {
                        TCPConnection connection = new TCPConnection(client, this.Receive, false);

                        this.connectionList.Add(connection);

                        return true;
                    }
                    else
                    {
                        client.Close();
                    }
                }

                if (!(this.isHost))
                    this.listener.Stop();

                return false;
            }
Esempio n. 36
0
 public void ConnectionClosed(TCPConnection conn)
 {
     logger.Debug("{0} closed.", conn);
 }
 void Awake()
 {
     //add a copy of TCPConnection to this game object
             myTCP = gameObject.AddComponent<TCPConnection> ();
             instance = this;
 }
Esempio n. 38
0
 public TelnetController()
 {
     telnetClient = new TCPConnection();
     encoder = new ASCIIEncoding();
 }
Esempio n. 39
0
 public void main()
 {
     listener = new TcpListener(IPAddress.Any, Port);
     listener.Start();
     while (true)
     {
         if (listener.Pending())
         {
             TCPConnection c = new TCPConnection(listener.AcceptTcpClient());
             Console.WriteLine("Connection Added");
             connections.Add(c);
         }
         foreach (TCPConnection c in Connections)
         {
             if (!c.Alive)
             {
                 Console.WriteLine("Connection Lost");
                 c.Kill();
                 connections.Remove(c);
                 break;
             }
             if (c.TimedOut)
             {
                 Console.WriteLine("Connection TimedOut");
                 c.Kill();
                 connections.Remove(c);
                 break;
             }
         }
         Thread.Sleep(20);
     }
 }
 // Receive message from TCP connection
 private void Receive(TCPConnection connection, IGridforceMessage message)
 {
     if (this.OnMessageReceived != null)
         this.OnMessageReceived(connection, message);
 }
            // Listen for connection requests
            public bool Listen()
            {
                if (this.connectionList.Count < 4 && this.listener.Pending() && this.isHost)
                {
                    TCPConnection connection = new TCPConnection(this.listener.AcceptTcpClient(), this.Receive, false);

                    this.connectionList.Add(connection);

                    return true;
                }

                return false;
            }
            // Connect to specific IP address
            public bool ConnectTo(string remoteIP, bool isHost)
            {
                try
                {
                    TcpClient client = new TcpClient(AddressFamily.InterNetwork);
                    client.Connect(IPAddress.Parse(remoteIP), NetworkComponents.gamePort);

                    TCPConnection connection = new TCPConnection(client, this.Receive, isHost);

                    this.connectionList.Add(connection);

                    return true;
                }
                catch (SocketException)
                {
                    return false;
                }

                return false;
            }
Esempio n. 43
0
        /// <summary>
        /// Upon a socket error on a remote client, it will be shutdown and removed from the system
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="e"></param>
        /// 
        public void OnSocketException(TCPConnection client, SocketException e)
        {
            //KTODO Handle specific exception
            Log.error("Remote Client {0} exception has occured." + ((SocketError)e.ErrorCode).ToString(), client.ClientID);

            client.Disconnect();
            RemoveClient(client.ClientID);
        }
 public TCPConnectionChangedEventArgs(TCPConnection connection)
 {
     Connection = connection;
 }
        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;
        }
Esempio n. 46
0
        private void device_PcapOnPacketArrival(object sender, Packet packet)
        {
            if (!(packet is TCPPacket)) return;

            TCPPacket tcpPacket = (TCPPacket)packet;
            // Creates a key for the dictionary
            TCPConnection c = new TCPConnection(tcpPacket);

            // create a new entry if the key does not exists
            if (!sharpPcapDict.ContainsKey(c) && !this.gotLock)
            {
                TcpRecon.TcpRecon tcpRecon = new TcpRecon.TcpRecon(this.serverStr, this.clientStr);
                sharpPcapDict.Add(c, tcpRecon);
                this.gotLock = true;
                this.connection = tcpRecon;
            }

            // Use the TcpRecon class to reconstruct the session
            if (this.sharpPcapDict.ContainsKey(c))
            {
                // Events
                if (tcpPacket.Syn && tcpPacket.Ack)
                    this.OnSynRecived(this);
                else if (tcpPacket.Fin && tcpPacket.Ack)
                    this.OnFinRecived(this);
                sharpPcapDict[c].ReassemblePacket(tcpPacket);
            }

            this.processPackets();
        }