Program() { IPAddress ip = Info.GetIp(); TcpListener listener = new TcpListener(ip,Info.Port); storage = new DataStorage(); listener.Start(); int counter = 0; Console.WriteLine("Server started: {0}",DateTime.Now); Console.WriteLine("Server ip: {0}", ip); Console.WriteLine("Server port: {0}",Info.Port); while (true) { TcpClient newClient = listener.AcceptTcpClient(); if (!IsMonitor(newClient)) { counter++; Console.WriteLine("is client"); Client client = new Client(newClient, this, counter, storage); clients.Add(client); } else if (_monitor != null) { if (!_monitor.TcpClient.Connected) { _monitor = new Monitor(newClient,this,clients, storage); } } else { _monitor = new Monitor(newClient,this,clients, storage); } } }
/// <summary> /// Registro. /// </summary> /// <param name="client"></param> /// <param name="name"></param> /// <param name="password"></param> static void HandleRegister (Client client, string name, string password) { var user = from u in Users where u.Name == name select u; if (user.Count () <= 0) { Users.Add (new User (name, password)); Send (client, REGISTER, "success"); } else { Send (client, LOGIN, "wu"); } }
/// <summary> /// It gets a request from network, process it, and returns response /// </summary> /// <returns>Returns response message</returns> public string ProcessIncomingRequest(string request, Client client) { string[] requestSplit = request.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries); string response = null; #if DEBUG Console.WriteLine("Processing request: "+ request); Console.WriteLine("RequestSplit[0]: " + requestSplit[0]); #endif switch (requestSplit[0]) { case "PUBLICKEY-REQUEST": client.GenerateNewKeys(); response = "PUBLICKEY-RESPONSE_" + client.GetPublicKey(); break; case "LOGIN": response = ProcessLoginRequest(requestSplit, client); break; case "REGISTER": response = ProcessRegisterRequest(requestSplit, client); break; case "PING": client.UpdateDestructionTime(); response = "OK"; break; } #if DEBUG Console.WriteLine("Request processed_Response is: " + response); #endif return response; }
public void SetHighestBid(Client client, double bid) { lock (_bidLock) { _highestbidder = client; _currentprice = bid; } }
private void ClientConnectedAsync(Socket socket) { var clientId = Interlocked.Increment(ref _clientCounter); var client = new Client(clientId, socket); lock (_clients) _clients.Add(client.Id, client); Console.WriteLine("Client connected: " + client.RemoteAddr); }
public static void Registration(Socket socket) { Client client = new Client(socket, id++); clients.Add(client); client.Send(new RegistrationResultMessage(client.Id)); Task task = new Task(client.Listen); task.Start(); }
/// <summary> /// Login. /// </summary> /// <param name="client"></param> /// <param name="name"></param> /// <param name="password"></param> static void HandleLogin (Client client, string name, string password) { var user = from u in Users where u.Name == name && u.Password == password select u; if (user.Count () > 0) { client.Name = name; client.Group = user.First ().Group; Send (client, LOGIN, "allow"); } else { Send (client, LOGIN, "wp"); } }
public void RemoveUser(Client c) { foreach (Client client in clients) { if(client.Equals(c)) { clients.Remove(client); } } }
public Peer(string name, string apiEndpoint, string accountId, string appName, string sceneId, bool canAttack) { _name = name; _app = appName; _accountId = accountId; _sceneId = sceneId; _apiEndpoint = apiEndpoint; var config = Stormancer.ClientConfiguration.ForAccount(accountId, appName); config.AddPlugin(new Stormancer.Authentication.AuthenticationPlugin()); config.AsynchrounousDispatch = false; config.ServerEndpoint = apiEndpoint; _client = new Client(config); }
public Auction(string name, string description, double estimatedPrice, double currentPrice, Client highestBidder) { this._name = name; this._description = description; this._estimatedprice = estimatedPrice; this._currentprice = currentPrice; this._highestbidder = highestBidder; this._timeLeft = 17000; // Timer this.Timer = new System.Timers.Timer(); this.Timer.Interval = 1000; }
public bool Connect(string ID) { bool Stoppable = true; Thread Stopper = new Thread(new ThreadStart(() => { Thread.Sleep(10 * 1000); try { if (Stoppable) { Listener.EndConnect(null); } } catch { } })); try { Stopper.Start(); while (Connection == null) { Client NewClient = new Client(Listener.Accept()); Stoppable = false; Stopper.Abort(); string ClientID = NewClient.Receive(); if (ClientID == ID) { // Match NewClient.Send("1"); Connection = NewClient; return true; } else { // Invalid client NewClient.Send("0"); } } } catch { return false; } return false; }
public bool Register(String name) { IServerCalback callback = OperationContext.Current.GetCallbackChannel<IServerCalback>(); foreach (Client c in clients) { if (c.name == name && c.callback.Equals(callback)) return false; } Client cl = new Client(); cl.name = name; cl.callback = callback; clients.Add(cl); return true; }
public void addRemoveOnlineList(Client client, string status) { if (status == "online") { serverModel.addUserToList(client); ServerView.writeToConsole("Client connected."); } if (status == "offline") { serverModel.removeUserFromList(client); ServerView.writeToConsole("Client disconnected."); } ServerView.writeToConsole("Online players: " + serverModel.onlineList.Count.ToString()); }
private void client_Disconnected(Client sender) { this.Invoke(() => { for (int i = 0; i < clientList.Items.Count; i++) { var client = clientList.Items[i].Tag as Client; if (client.Ip == sender.Ip) { txtReceive.Text += "<< " + clientList.Items[i].SubItems[1].Text + " has left the room >>\r\n"; BroadcastData("RefreshChat|" + txtReceive.Text); clientList.Items.RemoveAt(i); } } }); }
public static void TryCreateGame() { List<Client> tmp = clients.Where(x => x.search).ToList(); if (tmp.Count > 1) { if (tmp.Count % 2 == 1) { tmp.RemoveAt(tmp.Count - 1); } for (int i = 0; i < tmp.Count; i += 2) { Client[] newGamers = new Client[]{tmp[i], tmp[i+1]}; Game game = new Game(newGamers); } } }
public void UpdatePosition(Client.Input inputData, Stopwatch elapsedTime) { //Add force Velocity += inputData.InputDirection.Normalize() * ((float)elapsedTime.ElapsedMilliseconds / 1000); //Apply force Position += Velocity * ((float)elapsedTime.ElapsedMilliseconds / 1000); //Apply counterforce Velocity -= Velocity * 0.9995f * ((float)elapsedTime.ElapsedMilliseconds / 1000); if (Velocity.Lenght <= 0.01f) { Velocity = new Vector2(); } }
public Game(Client[] clients) { gamers = new Gamer[2]; bool turn = true; for (int i = 0; i < gamers.Length; i++) { gamers[i] = new Gamer(); gamers[i].turn = turn; gamers[i].client = clients[i]; gamers[i].client.Step += Step; turn = !turn; } BigStaticClass.logger.Log(gamers[0].client.nick + " и " + gamers[1].client.nick + " вошли в игру"); Start(); }
public ClientHandler(Socket clientSocket, Broadcaster broadcaster) { this._clientSocket = clientSocket; this._broadcaster = broadcaster; this._disconnected = false; _auction = null; /* Udskriver IP'en */ string clientIp = clientSocket.RemoteEndPoint.ToString(); client = new Client(clientIp); _broadcaster.Clients.Add(client); Console.WriteLine(clientIp +"("+client.Name+") connected"); }
/// <summary> /// Processing login request /// </summary> /// <param name="requestSplit">Format: LOGIN_username_password</param> /// <returns>Response message for client</returns> public string ProcessLoginRequest(string[] requestSplit, Client client) { //TODO: What if this user is already logged in ? (On different computer?) if (requestSplit.Length != 3) return null; string username = requestSplit[1]; string password = AsymmetricEncryption.DecryptText(requestSplit[2], client.GetKeySize(), client.GetPrivateKey()); List<string> userSelect = mainDatabase.SelectUsers(username, password); if (userSelect.Count == 1) { //We have to update status of our client to 'connected' SwitchClientIntoLoginState(client); return "LOGIN_OK"; } return "LOGIN_NOK"; }
public void AcceptListen() { bind(); listen(); Client client; while (true) { try { client_sock = listen_sock.Accept(); client_ip = (IPEndPoint)client_sock.RemoteEndPoint; client = new Client(client_sock,client_ip); th_client = new Thread(new ThreadStart(client.Receive)); } catch (Exception e) { MessageBox.Show(e.Message); break; } } }
/// <summary> /// Method that is performed when a new user is added. /// </summary> /// <param name="sender">The object that sent this message</param> /// <param name="user">The user that needs to be added</param> private void listener_userAdded(object sender, Client user) { connectedClients++; //Send a message to every other client notifying them on a new client, if the setting is set to True if (Properties.Settings.Default.SendMessageToClientsWhenAUserIsAdded) { writeStream.Position = 0; //Write in the form {Protocol}{User_ID}{User_IP} writer.Write(Properties.Settings.Default.NewPlayerByteProtocol); writer.Write(user.id); writer.Write(user.IP); SendData(GetDataFromMemoryStream(writeStream), user); } //Set up the events user.DataReceived += new DataReceivedEvent(user_DataReceived); user.UserDisconnected += new ConnectionEvent(user_UserDisconnected); //Print the new player message to the server window. Console.WriteLine(user.ToString() + " connected\tConnected Clients: " + connectedClients + "\n"); //Add to the client array client[user.id] = user; }
public void Load(Client client, Data receive, List<Client> clientList = null, List<Channel> channelsList = null) { Received = receive; Client = client; ListOfClientsOnline = clientList; }
public void AddToDictionary(Client client) { userID++; user.Add(client, userID); }
public void addUserToList(Client client) { onlineList.Add(client); }
public void removeUserFromList(Client client) { try { foreach (Client c in onlineList) { if (c.getId() == client.getId()) onlineList.RemoveAt(onlineList.IndexOf(c)); } } catch { } }
/// <summary> /// Method that is performed when a new user is disconnected. /// </summary> /// <param name="sender">The object that sent this message</param> /// <param name="user">The user that needs to be disconnected</param> private void user_UserDisconnected(object sender, Client user) { connectedClients--; //Send a message to every other client notifying them on a removed client, if the setting is set to True if (Properties.Settings.Default.SendMessageToClientsWhenAUserIsRemoved) { writeStream.Position = 0; //Write in the form {Protocol}{User_ID}{User_IP} writer.Write(Properties.Settings.Default.DisconnectedPlayerByteProtocol); writer.Write(user.id); writer.Write(user.IP); SendData(GetDataFromMemoryStream(writeStream), user); } //Print the removed player message to the server window. Console.WriteLine(user.ToString() + " disconnected\tConnected Clients: " + connectedClients + "\n"); //Clear the array's index client[user.id] = null; }
/// <summary> /// Relay messages sent from one client and send them to others /// </summary> /// <param name="sender">The object that called this method</param> /// <param name="data">The data to relay</param> private void user_DataReceived(Client sender, byte[] data) { writeStream.Position = 0; if (Properties.Settings.Default.EnableSendingIPAndIDWithEveryMessage) { //Append the id and IP of the original sender to the message, and combine the two data sets. writer.Write(sender.id); writer.Write(sender.IP); data = CombineData(data, writeStream); } //If we want the original sender to receive the same message it sent, we call a different method if (Properties.Settings.Default.SendBackToOriginalClient) { SendData(data); } else { SendData(data, sender); } }
/// <summary> /// Sends a message to every client except the source. /// </summary> /// <param name="data">Data to send</param> /// <param name="sender">Client that should not receive the message</param> private void SendData(byte[] data, Client sender) { foreach (Client c in client) { if (c != null && c != sender) { c.SendData(data); } } //Reset the writestream's position writeStream.Position = 0; }
/* * Saves the session for later viewing. */ internal static void SaveSession(Client client) { savedSession.Add(client.GetSessionData()); StorageController.Save(savedSession); }
/// <summary> /// Функция, которая постоянно прослушивает поток клиента /// </summary> /// <param name="obj"></param> private static void HandleClint(object obj) { Client client = (Client)obj; MemoryStream memoryStream = new MemoryStream(new byte[10000], 0, 10000, true, true); BinaryReader binaryReader = new BinaryReader(memoryStream); BinaryWriter binaryWriter = new BinaryWriter(memoryStream); while (true) { memoryStream.Position = 0; try { client.Socket.Receive(memoryStream.GetBuffer()); } catch (Exception) { foreach (var c in clients) { if (c == client) { clients.Remove(c); Console.WriteLine($"Пользователь {c.Name} отключился"); count--; ChangeIndex(); c.Socket.Shutdown(SocketShutdown.Both); c.Socket.Disconnect(true); return; } } return; } int code = binaryReader.ReadInt32(); int mark; int column, row, ships; bool attackSuccess = false; switch (code) { //Пакет, содержащий имя и адрес игрока case 0: k = 0; l = l + 1; client.Name = binaryReader.ReadString(); client.IPAdress = binaryReader.ReadString(); Console.WriteLine($"{client.Name} ({client.IPAdress}) в игре"); /*client.CheckThreadd = new Thread(CheckClient); * checkThread.Start(client);*/ Task.Run(() => { CheckClient(client); client.MainThread.Abort(); return; }); if (l != 2) { memoryStream.Position = 0; binaryWriter.Write(0); client.Socket.Send(memoryStream.GetBuffer()); break; } else { foreach (var c in clients) { memoryStream.Position = 0; binaryWriter.Write(1); c.Socket.Send(memoryStream.GetBuffer()); } break; } //Содержит готовность игроков к игре case 1: Console.WriteLine($"{client.Name} расставил корабли и готов к игре"); k = k + 1; if (k != 2) { memoryStream.Position = 0; binaryWriter.Write(2); client.Socket.Send(memoryStream.GetBuffer()); break; } if (k == 2) { foreach (var c in clients) { memoryStream.Position = 0; if (c.Index == 1) { binaryWriter.Write(3); binaryWriter.Write(true); c.Socket.Send(memoryStream.GetBuffer()); Console.WriteLine($"{c.Name}: атака"); } else { binaryWriter.Write(3); binaryWriter.Write(false); c.Socket.Send(memoryStream.GetBuffer()); } } } break; //Пакет, содержащий координаты атаки case 2: column = binaryReader.ReadInt32(); row = binaryReader.ReadInt32(); Console.Write($"{client.Name} атаковал: "); foreach (var c in clients) { if (c != client) { memoryStream.Position = 0; binaryWriter.Write(4); binaryWriter.Write(column); binaryWriter.Write(row); c.Socket.Send(memoryStream.GetBuffer()); } } break; //Пакет, содержащий ответ об атаке case 3: mark = binaryReader.ReadInt32(); if (mark == 2 || mark == 3) { Console.WriteLine("успешно!"); attackSuccess = true; } if (mark == 6) { Console.WriteLine("мимо!"); attackSuccess = false; } foreach (var c in clients) { if (c != client) { memoryStream.Position = 0; binaryWriter.Write(5); binaryWriter.Write(attackSuccess); binaryWriter.Write(mark); c.Socket.Send(memoryStream.GetBuffer()); } } break; //Пакет, определяющий ход игроков case 4: attackSuccess = binaryReader.ReadBoolean(); ships = binaryReader.ReadInt32(); if (ships == 0) { Console.WriteLine("Окончание игры!"); foreach (var c in clients) { if (c == client) { memoryStream.Position = 0; binaryWriter.Write(7); binaryWriter.Write(true); c.Socket.Send(memoryStream.GetBuffer()); Console.WriteLine($"Победитель {c.Name}"); } else { memoryStream.Position = 0; binaryWriter.Write(7); binaryWriter.Write(false); c.Socket.Send(memoryStream.GetBuffer()); } } break; } if (attackSuccess == true) { foreach (var c in clients) { if (c == client) { memoryStream.Position = 0; binaryWriter.Write(6); binaryWriter.Write(true); c.Socket.Send(memoryStream.GetBuffer()); Console.WriteLine($"{c.Name}: атака"); } else { memoryStream.Position = 0; binaryWriter.Write(6); binaryWriter.Write(false); c.Socket.Send(memoryStream.GetBuffer()); } } } else { foreach (var c in clients) { if (c == client) { memoryStream.Position = 0; binaryWriter.Write(6); binaryWriter.Write(false); c.Socket.Send(memoryStream.GetBuffer()); } else { memoryStream.Position = 0; binaryWriter.Write(6); binaryWriter.Write(true); c.Socket.Send(memoryStream.GetBuffer()); Console.WriteLine($"{c.Name}: атака"); } } } break; } } }
public void AddUser(Client client) { clients.Add(client); }
/// <summary> /// Listens on the listenerSocket for new connections, and constructs new clientData when found. /// </summary> private static void ListenerTask() { while (true) { //Prepare clientdata and set it to next Accepted connection (Blocks thread until one appears) Client newClient = new Client(listenerSocket.Accept()); //Sends registration packet Packet registrationPacket = new Packet(PacketType.Registration, ID); registrationPacket.stringData.Add(newClient.id); newClient.clientSocket.Send(registrationPacket.ToBytes()); //Adds the client on the server lock(clientsLock) { clients.Add(newClient); } //Debug Informer.AddEventInformation("A new client was added! Registration packet size: " + registrationPacket.ToBytes().Length); } }
/// <summary> /// Отправка данных определённому клиенту, определяемого по ссылке из списка клиентов. /// </summary> /// <param name="client">Ссылка на клиента</param> /// <param name="data">данные для отправки</param> /// <param name="NeedEncrypt">флаг необходимости шифрования</param> private void Send(Client client, String data, bool NeedEncrypt) { try { byte[] byteData = null; if (NeedEncrypt) { byteData = Encoding.ASCII.GetBytes(Crypto.Encrypt(data)); } else { byteData = Encoding.ASCII.GetBytes(data + "?"); } // Начинаем отправку данных. client.Socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); } catch (Exception ex) { WinLog.Write(ex.Message, System.Diagnostics.EventLogEntryType.Error); Console.WriteLine("Ошибка: {0}", ex.Message); } }
/* * Saves the clientData for later viewing. */ internal static void SaveClientData(Client client) { savedClientData.Add(client.GetClientCredentials()); StorageController.SaveClientCredentials(savedClientData); }
/// <summary> /// закрывает подключение и удаляет клиента из списка клиентов. /// </summary> /// <param name="cl">ссылка на клиента.</param> private void CloseConnection(Client cl) { cl.Socket.Close(); cl.IsActive = false; lock (_clients) _clients.Remove(cl); }
public static PoolConnection CreatePoolConnection(Client client, string url, int port, string login, string password) { string credential = url + port.ToString() + login + password; PoolConnection lpc, mypc = null; int batchCounter = 0; while (Connections.TryGetValue(credential + batchCounter.ToString(), out lpc)) { if (lpc.WebClients.Count > MainClass.BatchSize) { batchCounter++; } else { mypc = lpc; break; } } credential += batchCounter.ToString(); if (mypc == null) { CConsole.ColorInfo(() => { Console.WriteLine("{0}: initiated new pool connection", client.WebSocket.ConnectionInfo.Id); Console.WriteLine("{0} {1} {2}", login, password, url); }); mypc = new PoolConnection(); mypc.Credentials = credential; mypc.LastSender = client; mypc.TcpClient = new TcpClient(); Fleck.SocketExtensions.SetKeepAlive(mypc.TcpClient.Client, 60000, 1000); mypc.TcpClient.Client.ReceiveBufferSize = 4096 * 2; mypc.Login = login; mypc.Password = password; mypc.Port = port; mypc.Url = url; mypc.WebClients.TryAdd(client); Connections.TryAdd(credential, mypc); try { mypc.TcpClient.Client.BeginConnect(url, port, new AsyncCallback(ConnectCallback), mypc); } catch { } } else { Console.WriteLine("{0}: reusing pool connection", client.WebSocket.ConnectionInfo.Id); mypc.WebClients.TryAdd(client); if (mypc.LastJob != null) { ReceiveJob(client, mypc.LastJob, mypc.LastSolved); } else { Console.WriteLine("{0} no job yet.", client.WebSocket.ConnectionInfo.Id); } } client.PoolConnection = mypc; return(mypc); }