Ejemplo n.º 1
0
        public bool SendFileList(string[] files)
        {
            try
            {
                TcpClient         client  = new TcpClient(IPAddress.Loopback.ToString(), Configuration.TcpPort);
                ConnectionMessage message = new ConnectionMessage(MessageType.IpcBaseFolder, true, files[0]);
                //SendMessage(client.Client,message);
                SendMessage(client, message);
                message.MessageType = MessageType.IpcElement;
                for (int i = 1; i < files.Length - 1; i++)
                {
                    message.Message = files[i];
                    SendMessage(client, message);
                }
                message.Message = files[files.Length - 1];
                message.Next    = false;
                SendMessage(client, message);

                client.Close();
                return(true);
            }
            catch (SocketException)
            {
                //Most likely failed to connect
                return(false);
            }
        }
Ejemplo n.º 2
0
        public override void Init()
        {
            if (_init)
            {
                return;
            }



            //Enable Menu:
            Process       Process = Process.ThisProcess();
            ASCIIEncoding enc     = new ASCIIEncoding();

            Process.Write(enc.GetBytes("AAAAAA"), 0x890898);


            Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            zERROR.GetZErr(Process).Report(2, 'G', "GUC-Version: " + v.ToString(), 0, "Program.cs", 0);


            setupPlayer();

            ConnectionMessage.Write();

            PlayerKeyMessage.getPlayerKeyMessage().Init();

            _init = true;


            TurnLeftID  = oCNpc.Player(Process.ThisProcess()).GetModel().GetAniIDFromAniName("T_RUNTURNL");
            TurnRightID = oCNpc.Player(Process.ThisProcess()).GetModel().GetAniIDFromAniName("T_RUNTURNR");
            StartJumpID = oCNpc.Player(Process.ThisProcess()).GetModel().GetAniIDFromAniName("T_STAND_2_JUMP");
        }
Ejemplo n.º 3
0
        public Task Send(ConnectionMessage message)
        {
            if (!String.IsNullOrEmpty(message.Signal) &&
                message.Signals != null)
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.CurrentCulture,
                                        Resources.Error_AmbiguousMessage,
                                        message.Signal,
                                        String.Join(", ", message.Signals)));
            }

            if (message.Signals != null)
            {
                return(MultiSend(message.Signals, message.Value, message.ExcludedSignals));
            }
            else
            {
                Message busMessage = CreateMessage(message.Signal, message.Value);

                busMessage.Filter = GetFilter(message.ExcludedSignals);

                if (busMessage.WaitForAck)
                {
                    Task ackTask = _ackHandler.CreateAck(busMessage.CommandId);
                    return(_bus.Publish(busMessage).Then(task => task, ackTask));
                }

                return(_bus.Publish(busMessage));
            }
        }
Ejemplo n.º 4
0
        private void DisconnectClient()
        {
            var msg = new ConnectionMessage(Connection.Disconnect, User); //Send message to server about disconnecting

            Connector.Stream.Write(msg.Serialize());                      //Disconnect this client from server

            StopClient();
        }
Ejemplo n.º 5
0
    //evento propio S - se conectó un usuario ID 900
    void OnUserConnected(NetworkMessage netMsg)
    {
        print("user connected");
        var msg = new ConnectionMessage();

        msg.connections = NetworkServer.connections.Count;
        NetworkServer.SendToClient(netMsg.conn.connectionId, MaxPlayers, msg);
    }
Ejemplo n.º 6
0
        internal static Task Outgoing(IHubOutgoingInvokerContext context)
        {
            var message = new ConnectionMessage(context.Signal, context.Invocation)
            {
                ExcludedSignals = context.ExcludedSignals
            };

            return(context.Connection.Send(message));
        }
Ejemplo n.º 7
0
        internal static void SendMessage(TcpClient to, ConnectionMessage message)
        {
            using (var writer = new BinaryWriter(to.GetStream(), Encoding.BigEndianUnicode, true))
            {
                var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                using (var memory = new MemoryStream())
                {
                    formatter.Serialize(memory, message);
                    byte[] data = memory.ToArray();
                    writer.Write(data.Length);
                    writer.Write(data);
                }
            }

            /*
             * IFormatter formatter =
             *  new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             *
             * using (MemoryStream ms = new MemoryStream())
             * {
             *  formatter.Serialize(ms, message);
             *  byte[] data = ms.ToArray();
             *  NetworkStream ns = to.GetStream();
             *  byte[] dataSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(data.Length));
             *  ns.Write(dataSize, 0, dataSize.Length);
             *  ns.Flush();
             *  ns.Write(data, 0, data.Length);
             *  ns.Flush();
             * }
             */
            /*
             * string json = JsonConvert.SerializeObject(message);
             *
             * using (TextWriter textW = new StreamWriter(to.GetStream(), Encoding.UTF8,4096,true))
             * using (JsonWriter jsonW = new JsonTextWriter(textW)
             * {
             *  CloseOutput=false
             * }
             * )
             * {
             *  JObject jObject = JObject.Parse(json);
             *
             *  jObject.WriteTo(jsonW);
             *  jsonW.Flush();
             * }*/
            /*
             * NetworkStream ns = to.GetStream();
             * byte[] data = ConnectionMessage.Serialize(message);
             * byte[] dataSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Encoding.UTF8.GetByteCount(JsonConvert.SerializeObject(message))));
             * ns.Write(dataSize, 0, dataSize.Length);
             * ns.Flush();
             * ns.Write(data, 0, data.Length);
             * ns.Flush();
             */
        }
    public void ConnectionStatus(ConnectionMessage msg)
    {
        switch(msg){
        case ConnectionMessage.disconnected:
            lostConnection = true;
            break;
        case ConnectionMessage.playerDisconnected:

            break;
        }
    }
Ejemplo n.º 9
0
 public void ConnectionStatus(ConnectionMessage msg)
 {
     Debug.Log("network message to CreateGameGUI: "+msg);
     switch(msg){
     case ConnectionMessage.serverInit:
         FinishCreateGame();
         break;
     case ConnectionMessage.serverInitFailed:
         state = State.FailedToLaunchServer;
         break;
     }
 }
Ejemplo n.º 10
0
        private static Task SendCommand(ITransportConnection connection, string connectionId, CommandType commandType)
        {
            var command = new Command
            {
                CommandType = commandType
            };

            var message = new ConnectionMessage(PrefixHelper.GetConnectionId(connectionId),
                                                command);

            return(connection.Send(message));
        }
        private static Task SendCommand(ITransportConnection connection, string connectionId, CommandType commandType)
        {
            var command = new Command
            {
                CommandType = commandType
            };

            var message = new ConnectionMessage(PrefixHelper.GetConnectionId(connectionId),
                                                command);

            return connection.Send(message);
        }
Ejemplo n.º 12
0
        public void TestConnectionMessageUnwind()
        {
            //wait and get timeout
            Assert.IsFalse(Processor.ConnectionMessage().Wait(10));

            //process
            ConnectionMessage msg = (ConnectionMessage)Processor.ReceiveLine("{\"op\":\"connection\", \"connectionId\":\"aconnid\"}");

            //now unwound
            Assert.IsTrue(Processor.ConnectionMessage().Wait(10));
            Assert.AreEqual("aconnid", Processor.ConnectionMessage().Result.ConnectionId);
            Assert.AreEqual(ConnectionStatus.CONNECTED, Processor.Status);
        }
Ejemplo n.º 13
0
    public void ConnectionStatus(ConnectionMessage msg)
    {
        switch(msg){

        case ConnectionMessage.connected:
            EnterGame();
            joiningGame = false;
            break;
        case ConnectionMessage.connectFailed:
            joiningGame = false;
            failedToJoin = true;
            break;
        }
    }
Ejemplo n.º 14
0
        public void RequestImage(User from)
        {
            FileStream f         = null;
            Stopwatch  stopwatch = null;

            try
            {
                TcpClient         client  = new TcpClient(from.UserAddress.ToString(), from.TcpPortTo);
                ConnectionMessage message = new ConnectionMessage(MessageType.ProfileImageRequest, false, null);
                SendMessage(client, message);
                message = ReadMessage(client);
                if (message.MessageType == MessageType.ProfileImageResponse && message.Next == true)
                {
                    string p        = Path.GetTempPath() + "\\LANShare";
                    string basePath = p;
                    Directory.CreateDirectory(p);
                    string fileName = (from.SessionId as string).Substring(0, 64);
                    p = p + fileName + ".jpg";
                    if (File.Exists(p))
                    {
                        string ext       = ".jpg";
                        int    fileCount = -1;
                        do
                        {
                            fileCount++;
                        } while (File.Exists(basePath + fileName + "(" + fileCount.ToString() + ")" + ext));
                        p = basePath + fileName + "(" + fileCount.ToString() + ")" + ext;
                    }
                    f         = new FileStream(p, FileMode.Create, FileAccess.Write);
                    stopwatch = new Stopwatch();
                    stopwatch.Reset();
                    stopwatch.Restart();
                    new FileDownloadHelper().ReceiveFile(f, client, stopwatch);
                    f.Close();
                    stopwatch.Stop();
                    from.ProfilePicture = new BitmapImage(new Uri(p, UriKind.Relative));
                }
            }catch (SocketException ex)
            {
                f?.Close();
                stopwatch?.Stop();
            }
            catch (IOException ex)
            {
                Debug.WriteLine(ex.Message);
                f?.Close();
                stopwatch?.Stop();
            }
        }
Ejemplo n.º 15
0
        private void InitializeUserData()
        {
            var messageData = GetMessage();
            var msg         = new ConnectionMessage(messageData);

            if (!VersionVerifier.Verify(msg.Hash))
            {
                Stream.Write(new PostCodeMessage(11).Serialize());
                server.RemoveConnection(Id);

                return;
            }

            SendId();
            server.BroadcastMessage(msg, Id);
        }
        /// <summary>
        /// Process a line of json
        /// </summary>
        /// <exception cref="JsonException">Thrown if line was invalid json</exception>
        /// <param name="line"></param>
        public ResponseMessage ReceiveLine(string line)
        {
            //clear last response
            ResponseMessage message = null;

            LastResponseTime = DateTime.UtcNow;
            var    time      = Stopwatch.StartNew();
            string operation = GetOperation(new JsonTextReader(new StringReader(line)));

            switch (operation)
            {
            case RESPONSE_CONNECTION:
                Trace.TraceInformation("ESA->Client: {0}", line);
                ConnectionMessage connectionMessage = ReadResponseMessage <ConnectionMessage>(line);
                message = connectionMessage;
                ProcessConnectionMessage(connectionMessage);
                break;

            case RESPONSE_STATUS:
                Trace.TraceInformation("ESA->Client: {0}", line);
                StatusMessage statusMessage = ReadResponseMessage <StatusMessage>(line);
                message = statusMessage;
                ProcessStatusMessage(statusMessage);
                break;

            case RESPONSE_MARKET_CHANGE_MESSAGE:
                TraceChange(line);
                MarketChangeMessage marketChangeMessage = ReadResponseMessage <MarketChangeMessage>(line);
                message = marketChangeMessage;
                ProcessMarketChangeMessage(marketChangeMessage);
                break;

            case RESPONSE_ORDER_CHANGE_MESSAGE:
                TraceChange(line);
                OrderChangeMessage orderChangeMessage = ReadResponseMessage <OrderChangeMessage>(line);
                message = orderChangeMessage;
                ProcessOrderChangeMessage(orderChangeMessage);
                break;

            default:
                Trace.TraceError("ESA->Client: Unknown message type: {0}, message:{1}", operation, line);
                break;
            }
            time.Stop();

            return(message);
        }
Ejemplo n.º 17
0
        public Task Send(ConnectionMessage message)
        {
            Message busMessage = CreateMessage(message.Signal, message.Value);

            if (message.ExcludedSignals != null)
            {
                busMessage.Filter = String.Join("|", message.ExcludedSignals);
            }

            if (busMessage.WaitForAck)
            {
                Task ackTask = _ackHandler.CreateAck(busMessage.CommandId);
                return(_bus.Publish(busMessage).Then(task => task, ackTask));
            }

            return(_bus.Publish(busMessage));
        }
Ejemplo n.º 18
0
        public bool StartClient()
        {
            Connector.StartClient(receiveThread, listenThread);

            var joiningMessage = new ConnectionMessage(Connection.Connect, User);

            SendMessage(joiningMessage);

            Cmd.WriteLine("Successfully connected to the server");

            receiveMessage = true;

            receiveThread = new Thread(ReceiveMessage);    //Starting receive message thread
            receiveThread.Start();

            return(true);
        }
Ejemplo n.º 19
0
    private void setClient(ConnectionMessage connectionMessage)
    {
        print("set client called");

        connectButton.enabled = false;
        connectButton.gameObject.SetActive(false);

        // usernameText.text = connectionMessage.playerName;

        //this.CurrentUsername = connectionMessage.username;

        this.CurrentPlayerName = connectionMessage.playerName;

        playerNameText.text = connectionMessage.playerName;

        print(connectionMessage.username + " player " + connectionMessage.playerName);
    }
Ejemplo n.º 20
0
        public void SendConnection(SwitchConnection conn)
        {
            var scr = new ConnectionEnd()
            {
                Id     = conn.Source.Address,
                Volumn = (byte)conn.Source.Volumn,
                Status = conn.Source.IsConnected ? eStatus.On : eStatus.Off
            };

            var dest = new ConnectionEnd()
            {
                Id     = conn.Dest.Address,
                Volumn = (byte)conn.Dest.Volumn,
                Status = conn.Dest.IsConnected ? eStatus.On : eStatus.Off
            };

            var msg = new ConnectionMessage()
            {
                Source = scr,
                Dest   = dest
            };

            this.Presentation.SendData(msg);
        }
Ejemplo n.º 21
0
        static void Incoming()
        {
            NetIncomingMessage msg;
            while ((msg = Server.ReadMessage()) != null)
            {
                switch (msg.MessageType)
                {
                    case NetIncomingMessageType.DiscoveryRequest:
                        Console.WriteLine("Request from "+msg.SenderEndpoint.Address + " - Port " + msg.SenderEndpoint.Port);
                        NetOutgoingMessage reply = Server.CreateMessage();
                        reply.Write(Version);
                        Server.SendDiscoveryResponse(reply, msg.SenderEndpoint);
                        Console.WriteLine("Sending response to:" + msg.SenderEndpoint.Address + " - Port " + msg.SenderEndpoint.Port);
                        break;

                    case NetIncomingMessageType.StatusChanged:
                        NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
                        Console.WriteLine(msg.SenderEndpoint.Address + " " + status);
                        break;

                    case NetIncomingMessageType.Data:
                        Manager.HandleData(msg);
                        break;

                    case NetIncomingMessageType.UnconnectedData:
                        var datatype = (NetMsgType)msg.ReadByte();
                        if (datatype == NetMsgType.Login)
                        {
                            var udata = new ConnectionMessage(msg);
                            if (!UserData.UserExists(udata.Username))
                            {
                                UserData.Add(udata.Username, udata.Password);
                                var outmsg = Server.CreateMessage();
                                outmsg.Write((byte)ConnectMsgType.NewUserCreated);
                                Server.SendUnconnectedMessage(outmsg, msg.SenderEndpoint);
                            }
                            else
                            {
                                if (UserData.Check(udata.Username, udata.Password))
                                {
                                    var outmsg = Server.CreateMessage();
                                    outmsg.Write((byte)ConnectMsgType.LoginSuccess);
                                    Server.SendUnconnectedMessage(outmsg, msg.SenderEndpoint);
                                }
                                else
                                {
                                    var outmsg = Server.CreateMessage();
                                    outmsg.Write((byte)ConnectMsgType.WrongPassword);
                                    Server.SendUnconnectedMessage(outmsg, msg.SenderEndpoint);
                                }
                            }
                        }
                        break;
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.Error:
                    case NetIncomingMessageType.ErrorMessage:
                    case NetIncomingMessageType.WarningMessage:
                        Console.WriteLine(msg.ReadString());
                        break;

                    default:
                        Console.WriteLine("Unhandled Message Type: " + msg.MessageType);
                        break;
                }
                Server.Recycle(msg);
            }
        }
Ejemplo n.º 22
0
        internal static Task Outgoing(IHubOutgoingInvokerContext context)
        {
            ConnectionMessage message = context.GetConnectionMessage();

            return(context.Connection.Send(message));
        }
Ejemplo n.º 23
0
    // this will construct a connection using the given source,
    // and destination entities, relationship type and value
    // and send that to the message handler
    public void SendConnectionMessage()
    {
        InputField weightInput = GameObject.FindGameObjectWithTag("Weight").GetComponent<InputField>();
        SetActiveCastMember();

        // first we build the connection to send by fetching the values we set in the
        // UI

        // get the weight and store it as an int
        string weightString = weightInput.text;
        int weight = int.Parse(weightString);

        RelationshipType type = activeRelationshipType;
        Relationship rel = new Relationship(type, weight);

        GameObject to = activeCastMember;

        // our "from" attribute is always the castLead for this demo
        Connection connection = new Connection(castLead, to, rel);

        // then we send it
        ConnectionMessage connMessage = new ConnectionMessage(connection);
        castLead.GetComponent<Demo3Character>().HandleMessage(connMessage);
    }
Ejemplo n.º 24
0
        public void TestExtraJsonField()
        {
            ConnectionMessage msg = (ConnectionMessage)Processor.ReceiveLine("{\"op\":\"connection\", \"connectionId\":\"aconnid\", \"extraField\":\"extraValue\"}");

            Assert.AreEqual("aconnid", msg.ConnectionId);
        }
Ejemplo n.º 25
0
        public void TestOpNotFirst()
        {
            ConnectionMessage msg = (ConnectionMessage)Processor.ReceiveLine("{\"connectionId\":\"aconnid\", \"op\":\"connection\"}");

            Assert.AreEqual("aconnid", msg.ConnectionId);
        }
Ejemplo n.º 26
0
 private void OnConnectionSucess(string message)
 {
     ConnectionMessage?.Invoke(this, message);
 }
Ejemplo n.º 27
0
        public Task Send(ConnectionMessage message)
        {
            Message busMessage = CreateMessage(message.Signal, message.Value);

            if (message.ExcludedSignals != null)
            {
                busMessage.Filter = String.Join("|", message.ExcludedSignals);
            }

            if (busMessage.WaitForAck)
            {
                Task ackTask = _ackHandler.CreateAck(busMessage.CommandId);
                return _bus.Publish(busMessage).Then(task => task, ackTask);
            }

            return _bus.Publish(busMessage);
        }
Ejemplo n.º 28
0
 public void ConnectionStatus(ConnectionMessage msg)
 {
     AddLogEntry("Network update: "+msg);
 }
Ejemplo n.º 29
0
        public void Process()
        {
            try
            {
                Stream = client.GetStream();    //Gets stream

                InitializeUserData();           //Gets userData

                while (true)
                {
                    try
                    {
                        var message = GetMessage();  //While stream is available lets read stream
                        if (message.Length > 0)      //If message is not empty
                        {
                            var msg = IMessageDeserializable.Parse(message);

                            switch (msg.PostCode)
                            {
                            case { } i when(i >= 1 && i <= 4):
                            {
                                server.Notification();
                                server.BroadcastMessage(msg, Id);       //If this is regular message then broadcast it
                                break;
                            }

                            case 6:                                             //if client updates his UserData
                            {
                                var userDataMessage = msg as UserDataMessage;
                                if (userDataMessage?.Method == Method.Send)
                                {
                                    user = new User(userDataMessage?.Sender.UserName, userDataMessage.Sender.Color);     //Update UserData on server
                                }
                                break;
                            }

                            case 7:
                            {
                                var idMessage = msg as IDMessage;
                                if (idMessage?.Method == Method.Get)
                                {
                                    var sendMessage = new IDMessage(Method.Send, Id);
                                    Stream.Write(sendMessage.Serialize());
                                }

                                break;
                            }

                            case 9:                                     //If user Disconnecting
                            {
                                server.BroadcastMessage(msg, Id);       //Broadcast it
                                server.RemoveConnection(Id);            //And remove connection
                                break;
                            }

                            default:
                            {
                                continue;
                            }
                            }
                        }
                    }
                    catch
                    {
                        var disconnectionMsg = new ConnectionMessage(Connection.Disconnect, user);          //If there is error, disconnect this user
                        server.BroadcastMessage(disconnectionMsg, Id);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                server.RemoveConnection(Id);
                Close();
            }
        }
Ejemplo n.º 30
0
        private void HandleClient(TcpClient client, CancellationToken ct)
        {
            ConnectionMessage message = ReadMessage(client);

            if (message == null)
            {
                return;
            }
            switch (message.MessageType)
            {
            case MessageType.IpcBaseFolder:
                List <string> files = new List <string>();
                do
                {
                    files.Add(message.Message as string);
                    message = ReadMessage(client);
                } while (message.Next);
                files.Add(message.Message as string);
                OnSendRequested(files);
                break;

            case MessageType.ProfileImageRequest:
                Stopwatch stopwatch = null;
                try
                {
                    FileStream        f        = File.OpenRead(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + Configuration.UserPicPath);
                    ConnectionMessage response =
                        new ConnectionMessage(MessageType.ProfileImageResponse, true, null);
                    SendMessage(client, response);
                    stopwatch = new Stopwatch();
                    stopwatch.Reset();
                    stopwatch.Restart();
                    new FileUploadHelper().SendFile(f, client, stopwatch);
                    f.Close();
                    stopwatch.Stop();
                }
                catch (Exception ex)
                {
                    stopwatch?.Stop();
                    if (ex is FileNotFoundException || ex is DirectoryNotFoundException)
                    {
                        ConnectionMessage response =
                            new ConnectionMessage(MessageType.ProfileImageResponse, false, null);
                        SendMessage(client, response);
                    }
                }
                break;

            case MessageType.FileUploadRequest:
                User from = message.Message as User;
                from.UserAddress = ((IPEndPoint)client.Client.RemoteEndPoint).Address;
                from.NickName    = string.IsNullOrEmpty(from.NickName) || string.IsNullOrWhiteSpace(from.NickName) ? from.Name : from.NickName;
                string username = from.NickName != null ? from.NickName : from.Name;

                //TODO Ask user for permission
                if (Configuration.FileAcceptanceMode.Equals(EFileAcceptanceMode.AskAlways))
                {
                    bool rejected = false;
                    OnTransferRequested(from);
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        lock (l)
                        {
                            ConfirmationWindow C = new ConfirmationWindow("Incoming transfer from " + username + ".\nDo you want to accept it ?");
                            C.ShowDialog();
                            if (C.DialogResult == false)
                            {
                                message = new ConnectionMessage(MessageType.FileUploadResponse, false, null);
                                SendMessage(client, message);
                                rejected = true;
                            }
                        }
                    });

                    requestSeen?.Invoke(this, null);

                    if (rejected)
                    {
                        break;
                    }
                }
                //TODO Ask user for permission
                message = new ConnectionMessage(MessageType.FileUploadResponse, true, null);

                SendMessage(client, message);
                message = ReadMessage(client);
                if (message.MessageType != MessageType.TotalUploadSize)
                {
                    break;
                }

                //Ask for path to save files
                string savePath = null;
                if (Configuration.FileSavePathMode.Equals(EFileSavePathMode.AskForPath))
                {
                    FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                    folderBrowserDialog.Description = "Save transmission from " + username;
                    folderBrowserDialog.RootFolder  = Environment.SpecialFolder.Personal;
                    DialogResult dialogResult = folderBrowserDialog.ShowDialog();
                    if (dialogResult != DialogResult.OK)
                    {
                        break;
                    }
                    savePath = folderBrowserDialog.SelectedPath;
                }
                else if (Configuration.FileSavePathMode.Equals(EFileSavePathMode.UseCustom))
                {
                    savePath = Configuration.CustomSavePath;
                }
                else
                {
                    savePath = Configuration.DefaultSavePath;
                }


                FileDownloadHelper helper = new FileDownloadHelper();

                helper.Counterpart = from;
                from.UserAddress   = ((IPEndPoint)client.Client.RemoteEndPoint).Address;
                if (File.Exists(Path.Combine("tmp", from.SessionId + ".jpg")))
                {
                    from.ProfilePicture = new BitmapImage(new Uri(Path.Combine("tmp", from.SessionId + ".jpg"), UriKind.Relative));
                }
                else
                {
                    from.SetupImage();
                }
                helper.Status = TransferCompletitionStatus.Receiving;
                OnUploadAccepted(helper);

                helper.HandleFileDownload(client, savePath, (long)message.Message);
                break;
            }
            client.Close();
        }
 private void RelayConnectionStatus( ConnectionMessage msg)
 {
     //		foreach( INetworkMessage i in messageRecipients){
     //			i.ConnectionStatus(msg);
     //		}
     //
     for(int i=0; i<messageRecipients.Count;i++){
         messageRecipients[i].ConnectionStatus(msg);
     }
 }
Ejemplo n.º 32
0
        static void Incoming()
        {
            NetIncomingMessage msg;

            while ((msg = Server.ReadMessage()) != null)
            {
                switch (msg.MessageType)
                {
                case NetIncomingMessageType.DiscoveryRequest:
                    Console.WriteLine("Request from " + msg.SenderEndpoint.Address + " - Port " + msg.SenderEndpoint.Port);
                    NetOutgoingMessage reply = Server.CreateMessage();
                    reply.Write(Version);
                    Server.SendDiscoveryResponse(reply, msg.SenderEndpoint);
                    Console.WriteLine("Sending response to:" + msg.SenderEndpoint.Address + " - Port " + msg.SenderEndpoint.Port);
                    break;

                case NetIncomingMessageType.StatusChanged:
                    NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
                    Console.WriteLine(msg.SenderEndpoint.Address + " " + status);
                    break;

                case NetIncomingMessageType.Data:
                    Manager.HandleData(msg);
                    break;

                case NetIncomingMessageType.UnconnectedData:
                    var datatype = (NetMsgType)msg.ReadByte();
                    if (datatype == NetMsgType.Login)
                    {
                        var udata = new ConnectionMessage(msg);
                        if (!UserData.UserExists(udata.Username))
                        {
                            UserData.Add(udata.Username, udata.Password);
                            var outmsg = Server.CreateMessage();
                            outmsg.Write((byte)ConnectMsgType.NewUserCreated);
                            Server.SendUnconnectedMessage(outmsg, msg.SenderEndpoint);
                        }
                        else
                        {
                            if (UserData.Check(udata.Username, udata.Password))
                            {
                                var outmsg = Server.CreateMessage();
                                outmsg.Write((byte)ConnectMsgType.LoginSuccess);
                                Server.SendUnconnectedMessage(outmsg, msg.SenderEndpoint);
                            }
                            else
                            {
                                var outmsg = Server.CreateMessage();
                                outmsg.Write((byte)ConnectMsgType.WrongPassword);
                                Server.SendUnconnectedMessage(outmsg, msg.SenderEndpoint);
                            }
                        }
                    }
                    break;

                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.Error:
                case NetIncomingMessageType.ErrorMessage:
                case NetIncomingMessageType.WarningMessage:
                    Console.WriteLine(msg.ReadString());
                    break;

                default:
                    Console.WriteLine("Unhandled Message Type: " + msg.MessageType);
                    break;
                }
                Server.Recycle(msg);
            }
        }
Ejemplo n.º 33
0
        public void TestJsonMissingField()
        {
            ConnectionMessage msg = (ConnectionMessage)Processor.ReceiveLine("{\"op\":\"connection\"}");

            Assert.IsNotNull(msg);
        }
 protected void ProcessConnectionMessage(ConnectionMessage connectionMessage)
 {
     _connectionMessage.TrySetResult(connectionMessage);
     Status = ConnectionStatus.CONNECTED;
 }
 /// <summary>
 /// Constructs a new object.
 /// </summary>
 /// <param name="type"></param>
 /// <param name="response"></param>
 public HandshakeResponse(HandshakeType type, ConnectionMessage response)
 {
     this.type     = type;
     this.response = response;
 }
Ejemplo n.º 36
0
    private void setOtherPlayers(ConnectionMessage connectionMessage)
    {
        gameObjectShow(avatar);

        displayMessage("");
    }
Ejemplo n.º 37
0
        public Task Send(ConnectionMessage message)
        {
            if (!String.IsNullOrEmpty(message.Signal) &&
                message.Signals != null)
            {
                throw new InvalidOperationException(
                    String.Format(CultureInfo.CurrentCulture,
                                  Resources.Error_AmbiguousMessage,
                                  message.Signal,
                                  String.Join(", ", message.Signals)));
            }

            if (message.Signals != null)
            {
                return MultiSend(message.Signals, message.Value, message.ExcludedSignals);
            }
            else
            {
                Message busMessage = CreateMessage(message.Signal, message.Value);

                busMessage.Filter = GetFilter(message.ExcludedSignals);

                if (busMessage.WaitForAck)
                {
                    Task ackTask = _ackHandler.CreateAck(busMessage.CommandId);
                    return _bus.Publish(busMessage).Then(task => task, ackTask);
                }

                return _bus.Publish(busMessage);
            }
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Constructs a new object.
 /// </summary>
 /// <param name="response"></param>
 public LoginResponse(ConnectionMessage response)
 {
     this.response = response;
 }
Ejemplo n.º 39
0
 private void setOtherPlayers(ConnectionMessage connectionMessage)
 {
     displayMessage("");
 }
Ejemplo n.º 40
0
        protected override async Task ProcessParsedCommand(Message message)
        {
            await base.ProcessParsedCommand(message);

            switch (message.Type)
            {
            case PeerCommandType.CONNECTIONS:
            {
                var conectionsMessage = (ConnectionMessage)message;

                OnReceiveNumberOfConnections(conectionsMessage.ConnectionsAmount);
                break;
            }

            case PeerCommandType.DOWNLOAD_FILE_SLICE:
            {
                var downloadFileSliceMessage = (DownloadFileSliceMessage)message;

                OnDownloadFileSlice(downloadFileSliceMessage.File);
                break;
            }

            case PeerCommandType.GET_CONNECTIONS:
            {
                var numberOfConnections = await serverInstance.GetNumberOfConnectionsWithoutProcesor(ConnectedPeerInfo.Id);

                var connectionPeerMessage = new ConnectionMessage(numberOfConnections);

                Send(connectionPeerMessage);
                break;
            }

            case PeerCommandType.GET_FILE:
            {
                var fileMessage = (GetFileMessage)message;
                var file        = await serverInstance.GetAllSlicesOfFile(fileMessage.FileName);

                var downloadFileMessage = new DownloadFileMessage(file);

                Send(downloadFileMessage);
                break;
            }

            case PeerCommandType.GET_FILE_SLICE:
            {
                var fileMessage = (GetFileSliceMessage)message;
                var file        = await serverInstance.GetSlicesOfFile(fileMessage.FileName, ConnectedPeerInfo.Id);

                var downloadFileMessage = new DownloadFileSliceMessage(file);

                Send(downloadFileMessage);
                break;
            }

            case PeerCommandType.GET_KIND:
            {
                var kindOfConnectionMessage = new KindOfConnectionMessage(ConnectionType.PEER);

                Send(kindOfConnectionMessage);
                break;
            }

            case PeerCommandType.GET_LIST:
            {
                var files            = serverInstance.GetFiles();
                var listFilesMessage = new ListFilesMessage(files);

                Send(listFilesMessage);
                break;
            }

            case PeerCommandType.GET_INFO:
            {
                Send(new PeerInfoMessage(serverInstance.Info));
                break;
            }

            case PeerCommandType.PEER_INFO:
            {
                var infoMessage = (PeerInfoMessage)message;

                OnReceivePeerInfo(infoMessage.Info);
                break;
            }

            case PeerCommandType.UPLOAD_FILE:
            {
                var uploadFileMessage = (UploadFileMessage)message;

                Console.WriteLine($"Receive file to upload => {uploadFileMessage.FileName}, {uploadFileMessage.FileBytes.Length}");

                await serverInstance.UploadFile(uploadFileMessage.FileName, uploadFileMessage.FileBytes);

                break;
            }

            case PeerCommandType.UPLOAD_FILE_SLICE:
            {
                var fileMessage = (UploadFileSliceMessage)message;
                var file        = fileMessage.File;

                await serverInstance.SaveAndShare(file, ConnectedPeerInfo.Id);

                break;
            }
            }
        }