public override void ProcessMessage(byte[] data, AClient client) { try { if (filesize == 0) { filesize = BitConverter.ToInt64(data, 0); } else if (filename == "") { filename = ASCIIEncoding.ASCII.GetString(data); fs = new FileStream(Settings.GetDefaultUploadLocation() + filename, FileMode.CreateNew); } else { fs.Write(data, 0, data.Length); bytesread += data.Length; if (bytesread == filesize) { fs.Close(); CompleteJob(); } } } catch (Exception ex) { Core.HandleEx("ServerFileUploadJob", ex); } }
public override void ProcessMessage(byte[] data, AClient client) { // Signal server to end its job. client.Send(new PPMessage(true, this.JobNumber, this.RemoteJobNumber).GetEncodedData()); Core.Output("Client Philes Job " + JobNumber + " complete."); CompleteJob(); }
/// <summary> /// This method can be overriden in a controller class to provide more specific Authorize for certain actions /// </summary> /// <param name="endPoint"></param> /// <param name="authTokenObject"></param> /// <param name="userId"></param> /// <returns></returns> protected HttpResponseMessage Authorize(string endPoint, AuthToken authTokenObject, int userId) { if (authTokenObject == null || authTokenObject.ClientId == 0) { return(this.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid or missing required Auth Token", endPoint)); } if (string.IsNullOrEmpty(authTokenObject.ApiName) || authTokenObject.ClientId < 1) { return(this.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid or missing required data (AuthToken is invalid)", endPoint)); } if (!endPoint.StartsWith(authTokenObject.ApiName)) { return(this.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid Authentication Token", endPoint)); } AClient client = Master.Clients.GetClientById(authTokenObject.ClientId); if (client == null) { return(this.CreateErrorResponse(HttpStatusCode.Forbidden, "Client is invalid", endPoint)); } if (userId > 0 && (client.ClientUsers == null || client.ClientUsers.All(x => x.Id != userId))) { return(this.CreateErrorResponse(HttpStatusCode.Forbidden, "This UserId is not valid for this client", endPoint)); } return(null); }
public void ReceiveData(byte[] encodedData, AClient client) { PPMessage message = new PPMessage(encodedData); if (message.ConnectionEstablished) { // If we receive a message for a job that doesn't exist. if (Jobs[message.ReceiverJobNumber] == null) { return; // TODO: Tell client to cancel its job. } // Otherwise give the job the data to be processed. Jobs[message.ReceiverJobNumber].ProcessMessage(message.Message, client); } else { // Create a new job depending on what type the client requests. PhilesJobType newJobType = (PhilesJobType)message.ReceiverJobNumber; int newJobNumber = Jobs.AddJob(newJobType); Jobs[newJobNumber].RemoteJobNumber = message.SenderJobNumber; // Send a blank response to client signaling its okay to start transmission. PPMessage serverResponse = new PPMessage(true, newJobNumber, message.SenderJobNumber); client.Send(serverResponse.GetEncodedData()); } }
public Player(AClient client, string name, byte slot) { _client = client; _name = name; _slot = slot; _position = Vector2.Zero; _velocity = Vector2.Zero; }
public frmTClient() { InitializeComponent(); PCP = new PhilesClientProtocol(); Socket underlying = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Client = new AClient(underlying, false); }
// (3) Maintaining Socket For Each Client private static void Add_Client(Socket sockClient) { AudioNewclient = new AClient(sockClient); AudioClientsList.Add(AudioNewclient); AudioNewclient.SetupRecieveCallback(); }
public Program() { try { Console.WriteLine("Enter your connection method:"); Console.WriteLine("1. IP"); Console.WriteLine("2. Steam"); char choice; do { choice = Console.ReadKey().KeyChar; } while (choice != '1' && choice != '2'); string ip; if (choice == '1') { client = new IPClient(); Console.Clear(); Console.WriteLine("Enter IP address (localhost):"); ip = Console.ReadLine(); if (ip == "") ip = "localhost"; } else { client = new SteamClient(); Console.Clear(); Console.WriteLine("Enter Steam ID to join:"); ip = Console.ReadLine(); } client.ServerJoined += Ai; client.Log += Log; client.ChatMessageReceived += Chat; Console.Clear(); Console.WriteLine("Enter password if any:"); string password = Console.ReadLine(); Console.Clear(); if (choice == '1') { ((IPClient)client).ConnectWithIP(ip, myInfos, password); } else { ((SteamClient)client).ConnectWithSteamId(ulong.Parse(ip), myInfos, password); } } catch (SocketException se) { Console.WriteLine("Can't connect to server: " + se.Message + Environment.NewLine + "Make sure that your Terraria server is online."); Console.WriteLine("Press any key to continue"); Console.ReadKey(); return; } }
public Class40() { NetTcpBinding binding1 = new NetTcpBinding(SecurityMode.None) { PortSharingEnabled = true, MaxReceivedMessageSize = 0x7fffffffL }; binding1.ReaderQuotas.MaxArrayLength = 0x7fffffff; binding1.SendTimeout = new TimeSpan(0, 10, 0); NetTcpBinding binding = binding1; this.aclient_0 = new AClient(binding, endpointAddress_0); }
public override void ProcessMessage(byte[] data, AClient client) { try { FileInfo fi = new FileInfo(FileName); if (fi.Exists) { // Send Filesize long filesize = fi.Length; client.Send(new PPMessage(true, JobNumber, RemoteJobNumber, BitConverter.GetBytes(filesize)).GetEncodedData()); // Send Filename string filename = fi.Name; client.Send(new PPMessage(true, JobNumber, RemoteJobNumber, ASCIIEncoding.ASCII.GetBytes(filename)).GetEncodedData()); // Send File FileStream fs = File.OpenRead(FileName); byte[] buffer = new byte[2048]; // should be correct size to fit in packets, although doesnt really matter long bytessent = 0; while (bytessent < filesize) { if (filesize - bytessent >= buffer.Length) { fs.Read(buffer, 0, buffer.Length); client.Send(new PPMessage(true, JobNumber, RemoteJobNumber, buffer).GetEncodedData()); bytessent += buffer.Length; } else { int bytesread = fs.Read(buffer, 0, (int)(filesize - bytessent)); byte[] final = new byte[filesize - bytessent]; Array.Copy(buffer, 0, final, 0, bytesread); client.Send(new PPMessage(true, JobNumber, RemoteJobNumber, final).GetEncodedData()); bytessent += final.Length; } } fs.Close(); } else { Core.Output("File does not exist! '" + FileName + "'"); CompleteJob(); } } catch (Exception ex) { Core.HandleEx("ClientFileUploadJob:ProcessMessage", ex); } }
/// <summary> </summary> /// <param name="Object">The Class object to share with others</param> /// <param name="RemoteInitialize">False: The class will be initialized locally using the "ClassArgs" objects, /// True: The remote client will give the ClassArgs to use for initializing the object and will ignore the local argument objects</param> /// <param name="ClassArgs">The objects to initialize the class with</param> internal SharedClass(Type ClassType, AClient connection, bool RemoteInitialize = false, params object[] ClassArgs) { if (ClassType == null) throw new ArgumentNullException("Object"); if (!ClassType.IsClass) throw new Exception("Object is not a class"); this._Methods = new SortedList<string, List<SharedMethod>>(); this.BaseClassType = ClassType; this.BaseClassTypeArgs = ClassArgs; if (this.BaseClassTypeArgs == null) this.BaseClassTypeArgs = new object[0]; this.Name = ClassType.Name; this.connection = connection; this.ConstructorTypes = new List<Type[]>(); this.RemoteInitialize = RemoteInitialize; List<SharedMethod> methods = new List<SharedMethod>(); foreach (MethodInfo m in ClassType.GetMethods()) { if (!m.IsPublic || m.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 && m.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0) continue; SharedMethod sharedMethod = new SharedMethod(m, this); int token = m.MetadataToken; if (!_Methods.ContainsKey(m.Name)) _Methods.Add(m.Name, new List<SharedMethod>()); _Methods[m.Name].Add(sharedMethod); methods.Add(sharedMethod); sharedMethod.MethodId = methods.Count; } this.Methods = methods.ToArray(); foreach (ConstructorInfo m in ClassType.GetConstructors()) { if (!m.IsStatic && m.IsPublic && m.GetCustomAttributes(typeof(RemoteConstructorAttribute), false).Length > 0) { List<Type> list = new List<Type>(); foreach(ParameterInfo param in m.GetParameters()) list.Add(param.ParameterType); ConstructorTypes.Add(list.ToArray()); } } }
// (4) Send The Recieved Data to All Clients in The Room private static void OnRecievedData(IAsyncResult ar) { AClient client = (AClient)ar.AsyncState; byte[] aryRet = client.GetRecievedData(ar); if (aryRet.Length < 1) { client.ReadSocket.Close(); AudioClientsList.Remove(client); return; } else { Message dm = new Message(aryRet); if (dm.enumCommand == Command.Audio) { foreach (AClient cl in AudioClientsList) { try { if (cl.room != null) { if (dm.strRoom == cl.room) { cl.ReadSocket.NoDelay = true; cl.ReadSocket.Send(aryRet); } } } catch { cl.ReadSocket.Close(); AudioClientsList.Remove(cl); } } } else if (dm.enumCommand == Command.Join) { client.room = dm.strRoom; } client.SetupRecieveCallback(); } }
public void ReceiveData(byte[] encodedData, AClient client) { PPMessage message = new PPMessage(encodedData); // Unless the server starts refusing requests in the future, this // should never be false. if (message.ConnectionEstablished) { if (Jobs[message.ReceiverJobNumber] == null) { return; } if (Jobs[message.ReceiverJobNumber].RemoteJobNumber == -1) { Jobs[message.ReceiverJobNumber].RemoteJobNumber = message.SenderJobNumber; } Jobs[message.ReceiverJobNumber].ProcessMessage(message.Message, client); } }
public void BeginJob(PhilesJobType jobType, AClient client, object[] param) { if (jobType == PhilesJobType.JOB_CLIENT_PHILES) { int nJobCode = Jobs.AddJob(PhilesJobType.JOB_CLIENT_PHILES); PPMessage beginJobMessage = new PPMessage(false, nJobCode, (int)PhilesJobType.JOB_PHILES); client.Send(beginJobMessage.GetEncodedData()); } else if (jobType == PhilesJobType.JOB_CLIENT_DIRECTORY_LISTING) { int nJobCode = Jobs.AddJob(PhilesJobType.JOB_CLIENT_DIRECTORY_LISTING, param); PPMessage beginJobMessage = new PPMessage(false, nJobCode, (int)PhilesJobType.JOB_SERVER_DIRECTORY_LISTING); client.Send(beginJobMessage.GetEncodedData()); } else if (jobType == PhilesJobType.JOB_CLIENT_FILE_UPLOAD) { int nJobCode = Jobs.AddJob(PhilesJobType.JOB_CLIENT_FILE_UPLOAD, param); PPMessage beginJobMessage = new PPMessage(false, nJobCode, (int)PhilesJobType.JOB_SERVER_FILE_UPLOAD); client.Send(beginJobMessage.GetEncodedData()); } }
public override void ProcessMessage(byte[] data, AClient client) { try { if (State == ServerDirectoryRequestState.SDR_GET_FOLDER_NAME) { // Determine folder to give information on. string folder = ASCIIEncoding.ASCII.GetString(data); Core.Output("Server listing directory info for folder: '" + folder + "'"); // Compile a list of subfolders and files, package with string length // So the client can watch out for multiple packets. string response = getDirectoryInformation(folder); byte[] responseBytes = ASCIIEncoding.ASCII.GetBytes(response); client.Send(new PPMessage(true, this.JobNumber, this.RemoteJobNumber, responseBytes).GetEncodedData()); CompleteJob(); } } catch (Exception ex) { Core.HandleEx("ServerDirectoryRequestJob", ex); } }
public override void ProcessMessage(byte[] data, AClient client) { try { if (state == ClientDirectoryRequestState.CDR_SEND_DIRECTORY) { byte[] bDirectory = ASCIIEncoding.ASCII.GetBytes(RemoteDirectory); client.Send(new PPMessage(true, this.JobNumber, this.RemoteJobNumber, bDirectory).GetEncodedData()); //client.Send(EncapsulateDataWithSize(bDirectory)); state = ClientDirectoryRequestState.CDR_GET_RESULTS; } else if (state == ClientDirectoryRequestState.CDR_GET_RESULTS) { string response = ASCIIEncoding.ASCII.GetString(data, 0, data.Length); Core.Output("SERVER DIRECTORY LISTING\n------------------------\n" + response); CompleteJob(); } } catch (Exception ex) { Core.HandleEx("ClientDirectoryRequestJob:ProcessMessage", ex); } }
public virtual void ProcessMessage(byte[] data, AClient client) { Core.Output("Completed job " + JobNumber + ".", System.Drawing.Color.Green); CompleteJob(); }
/// <summary> /// Добавление кредита к клиенту /// </summary> /// <param name="credit">Кредит</param> /// <param name="client">Клиент</param> public static void Add(this CreditModel credit, AClient client) { client.AddCredit(credit); }
/// <summary> /// Добавление депозита клиенту /// </summary> /// <param name="deposit">Депозит</param> /// <param name="client">Клиент</param> public static void Add(this DepositModel deposit, AClient client) { client.AddDeposit(deposit); }
/// <summary> </summary> /// <param name="Object">The Class object to share with others</param> /// <param name="RemoteInitialize">False: The class will be initialized locally using the "ClassArgs" objects, /// True: The remote client will give the ClassArgs to use for initializing the object and will ignore the local argument objects</param> /// <param name="ClassArgs">The objects to initialize the class with</param> internal SharedClass(Type ClassType, AClient connection, bool RemoteInitialize = false, params object[] ClassArgs) { if (ClassType == null) { throw new ArgumentNullException("Object"); } if (!ClassType.IsClass) { throw new Exception("Object is not a class"); } this._Methods = new SortedList <string, List <SharedMethod> >(); this.BaseClassType = ClassType; this.BaseClassTypeArgs = ClassArgs; if (this.BaseClassTypeArgs == null) { this.BaseClassTypeArgs = new object[0]; } this.Name = ClassType.Name; this.connection = connection; this.ConstructorTypes = new List <Type[]>(); this.RemoteInitialize = RemoteInitialize; List <SharedMethod> methods = new List <SharedMethod>(); foreach (MethodInfo m in ClassType.GetMethods()) { if (!m.IsPublic || m.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 && m.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0) { continue; } SharedMethod sharedMethod = new SharedMethod(m, this); int token = m.MetadataToken; if (!_Methods.ContainsKey(m.Name)) { _Methods.Add(m.Name, new List <SharedMethod>()); } _Methods[m.Name].Add(sharedMethod); methods.Add(sharedMethod); sharedMethod.MethodId = methods.Count; } this.Methods = methods.ToArray(); foreach (ConstructorInfo m in ClassType.GetConstructors()) { if (!m.IsStatic && m.IsPublic && m.GetCustomAttributes(typeof(RemoteConstructorAttribute), false).Length > 0) { List <Type> list = new List <Type>(); foreach (ParameterInfo param in m.GetParameters()) { list.Add(param.ParameterType); } ConstructorTypes.Add(list.ToArray()); } } }
void Client_OnClientDisconnect(AClient c) { label2.Text = "NO"; button1.Text = "Connect"; }
public object onRequest(AClient connection, MsgGetSharedClass request) { ReturnResult result = new ReturnResult(null, false); lock(connection.SharingClasses) { try { if (connection.SharingClasses.ContainsKey(request.ClassName)) { SharedClass localSharedClass = connection.SharingClasses[request.ClassName]; if (localSharedClass.RemoteInitialize) { bool FoundConstructor = false; if (request.ArgObjects.Length > 0) { //lets check if there is a constructor with these arguments for (int i = 0; i < localSharedClass.ConstructorTypes.Count; i++) { if (localSharedClass.ConstructorTypes[i].Length == request.ArgObjects.Length) { bool CorrectArgs = true; for (int j = 0; j < request.ArgObjects.Length; j++) { if (localSharedClass.ConstructorTypes[i][j] != request.ArgObjects[j].GetType() && localSharedClass.ConstructorTypes[i][j] != request.ArgObjects[j].GetType().BaseType) { CorrectArgs = false; break; } } if (CorrectArgs) { FoundConstructor = true; break; } } } if (!FoundConstructor) return null; } } SharedClass sClass = new SharedClass(localSharedClass.BaseClassType, connection, localSharedClass.RemoteInitialize, localSharedClass.BaseClassTypeArgs); sClass.InitializedClass = Activator.CreateInstance(sClass.BaseClassType, localSharedClass.RemoteInitialize ? request.ArgObjects : sClass.BaseClassTypeArgs); Random rnd = new Random(DateTime.Now.Millisecond); int RandomId = rnd.Next(); while (connection.RemoteSharedClasses.ContainsKey(RandomId)) RandomId = rnd.Next(); sClass.SharedId = RandomId; connection.RemoteSharedClasses.Add(RandomId, sClass); result.ReturnValue = sClass; return result; } } catch (Exception ex) { result.ExceptionOccured = true; result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; } } return result; }
void Client_OnDataRead(byte[] data, AClient client) { PCP.ReceiveData(data, client); }
public TransactWindowView(AClient selectedItem) { InitializeComponent(); DataContext = new TransactViewModel(selectedItem); }
private HttpResponseMessage processXmlLead(HttpRequestMessage request, string encryptedClientId, int defaultUserId, string endpoint, bool checkForDuplicate = true) { this.ResponseFormatter = new XmlMediaTypeFormatter(); var startTime = DateTime.Now; if (string.IsNullOrEmpty(encryptedClientId)) { return(this.CreateErrorResponse(HttpStatusCode.BadRequest, "Missing encrypted client id.", endpoint)); } var clientId = NullSafe.NullSafeInteger(Encryption.DecryptString(encryptedClientId)); AClient client = Master.Lists.Clients.GetClientById(clientId); if (!client?.Active ?? true) //if null or not active reject... { return(this.CreateErrorResponse(HttpStatusCode.Unauthorized, "Client is invalid.", endpoint)); } //http://stackoverflow.com/questions/1127431/xmlserializer-giving-filenotfoundexception-at-constructor //Error is thrown here, this is 'expected' beaviour. Just ignore... var serializer = new XmlSerializer(typeof(MortgageLead)); var dataLead = (MortgageLead)serializer.Deserialize(request.Content.ReadAsStreamAsync().Result); ALeadsResponse response = new ALeadsResponse(); response.ApiEndPoint = endpoint; response.ClientDefinedIdentifier = dataLead.SourceLeadId; Lead lead; bool doInsert = true; if (checkForDuplicate) { ActionResponse <Lead> actionResponse = this.duplicateCheck(clientId, dataLead); if (actionResponse.Success) //true = dupicate { doInsert = false; response.Status = StatusType.Complete; response.Message = "Duplicate"; response.LoanTekDefinedIdentifier = actionResponse.DataObject.Id.ToString(); } } if (doInsert && (lead = LegacyLead.ConvertXmlSchema(dataLead)) != null) { lead.ClientID = clientId; //reset UserId to 0 if the User's ClientId does not match this client if (lead.UserID > 0 && Users.GetUserById(lead.UserID.GetValueOrDefault())?.ClientId != clientId) { lead.UserID = 0; } if (lead.UserID == 0) { lead.UserID = defaultUserId; } ActionResponse <Lead> actionResponse = new Biz.Contacts.Leads.Objects.Leads(DataContextType.Database, DataConnections.DataContextBankrateWrite).PutWithResponse(lead); if (actionResponse.Success) { response.Status = StatusType.Complete; response.Message = Types.Processing.StatusType.Success.ToString(); response.LoanTekDefinedIdentifier = actionResponse.DataObject?.Id.ToString(); } else { response.Status = StatusType.Error; response.Message = response.Message; } } response.ExecutionTimeInMillisec = (int)(DateTime.Now - startTime).TotalMilliseconds; return(Request.CreateResponse(HttpStatusCode.OK, response, this.ResponseFormatter)); }
public PlayerSelf(AClient client, string name, byte slot) : base(client, name, slot) { _lastActions = 0; new Thread(new ThreadStart(UpdatePosition)).Start(); }
public object onRequest(AClient connection, PayloadReader pr) { ReturnResult result = new ReturnResult(null, false); bool isDelegate = false; bool ReadFullHeader = false; try { int SharedClassId = pr.ReadInteger(); int MethodId = pr.ReadInteger(); isDelegate = pr.ReadByte() == 1; int DelegateId = isDelegate ? pr.ReadInteger() : 0; int DelegateClassId = isDelegate ? pr.ReadInteger() : 0; ReadFullHeader = true; if (connection.RemoteSharedClasses.ContainsKey(SharedClassId) || (isDelegate && connection.LocalSharedClasses.ContainsKey(DelegateClassId))) { SharedClass sClass = isDelegate ? connection.LocalSharedClasses[SharedClassId] : connection.RemoteSharedClasses[SharedClassId]; SharedMethod sharedMethod = sClass.GetMethod(MethodId); if (sharedMethod != null) { List<object> args = new List<object>(); List<Type> types = new List<Type>(); SortedList<int, SharedDelegate> SharedDelegates = new SortedList<int, SharedDelegate>(); SmartSerializer serializer = new SmartSerializer(); lock(sharedMethod.Delegates) { if(sharedMethod.Delegates.ContainsKey(DelegateId)) { for (int i = 0; i < sharedMethod.Delegates[DelegateId].sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } else { for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } } if (!isDelegate) //atm no support yet for delegate inside another delegate { for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++) { if (pr.ReadByte() == 1) { SharedDelegate del = pr.ReadObject<SharedDelegate>(); del.sharedMethod.sharedClass = sClass; args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del); SharedDelegates.Add(del.sharedMethod.DelegateId, del); } } } if (isDelegate) { //only show the result and not the actual ReturnResult type return sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray()); } else { MethodInfo m = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes); if (m.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 && m.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0) { return null; } result.ReturnValue = m.Invoke(sClass.InitializedClass, args.ToArray()); } } } } catch (Exception ex) { if (isDelegate && ReadFullHeader) throw ex; result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; result.ExceptionOccured = true; } return result; }
public void Send(PacketWriter pw, AClient except = null) => Values .SelectMany(x => x.Clients.Values) .Where(x => x.Key != except?.Key) .ToList() .ForEach(x => x.Send(pw));
public AddDepositMindowView(AClient holder) { InitializeComponent(); DataContext = new AddDepositViewModel(holder); }
/// <summary> /// Конструктор /// </summary> /// <param name="holder">Клиент</param> public NotEnoughtMoneyException(AClient holder) : base($"У клиента {holder} не хватает средств, для проведения операции.") { }