public void HandleClient(object obj) { // retrieve client from parameter passed to thread TcpClient client = (TcpClient)obj; // set two streams StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII); StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII); Boolean isConnected = true; String sData; while (isConnected) { // reads from stream try { sData = sReader.ReadLine(); if (sData == null) { break; } } catch (IOException e) { Console.WriteLine(e.Message); break; } Console.WriteLine("Got data from client: " + sData); if (sData.StartsWith("POST")) { ReceivedData.Add(sData.TrimStart(new char[] { 'P', 'O', 'S', 'T', ' ' })); } else if (sData.StartsWith("GET")) { if (ReceivedData.Count == 0) { sWriter.WriteLine("No words available."); } else { string[] splitString = ReceivedData[ReceivedData.Count - 1].Split(new char[] { ' ' }); ReceivedData.RemoveAt(ReceivedData.Count - 1); //"GET QS / BT / BS lorem ipsum string[] method = sData.Split(new char[] { ' ' }); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); switch (method[1]) { case "BS": { IEnumerable <IGrouping <string, string> > groupCount = splitString.GroupBy(w => w); List <Bubble> bubbles = new List <Bubble>(); foreach (IGrouping <string, string> group in groupCount) { bubbles.Add(new Bubble(group.Key, group.Count())); } bubbles = BubbleSort.Sort(bubbles); string s = ""; foreach (Bubble b in bubbles) { s = s + b.Word + " " + b.Count + ", "; } s = s.TrimEnd(new char[] { ',', ' ' }); stopWatch.Stop(); Console.WriteLine("BubbleSort finished sorting in: " + stopWatch.ElapsedMilliseconds); sWriter.WriteLine(s); break; } case "BT": { IEnumerable <IGrouping <string, string> > groupCount = splitString.GroupBy(w => w); BinaryTree <int, string> bt = new BinaryTree <int, string>(); foreach (IGrouping <string, string> group in groupCount) { bt.Add(group.Count(), group.Key); } stopWatch.Stop(); Console.WriteLine("BinaryTree finished sorting in: " + stopWatch.ElapsedMilliseconds); sWriter.WriteLine(bt.PrintTree(BinaryTree <int, string> .TraversalMethod.Inorder, BinaryTree <int, string> .TraversalDirection.Backwards)); break; } case "QS": { QuickSort qs = new QuickSort(); Dictionary <string, WordCount> wordCountDict = new Dictionary <string, WordCount>(); foreach (string temp in splitString) { if (wordCountDict.ContainsKey(temp)) { wordCountDict[temp].Count++; } else { wordCountDict.Add(temp, new WordCount(temp, 1)); } } WordCount[] wordCountList = new WordCount[wordCountDict.Count]; wordCountList = qs.Sort(wordCountDict.Values.ToArray()); string s = ""; for (int i = 0; i < wordCountList.Length; i++) { s = s + wordCountList[i].Word + " " + wordCountList[i].Count; if (i < wordCountList.Length - 1) { s = s + ", "; } } stopWatch.Stop(); Console.WriteLine("BinaryTree finished sorting in: " + stopWatch.ElapsedMilliseconds); sWriter.WriteLine(s); break; } default: { sWriter.WriteLine("No sorting method chosen."); break; } } } } else { sWriter.WriteLine("Wrong header"); } sWriter.Flush(); } Console.WriteLine("Connection closed to client."); }
static void ServerWorker(Object obj) { TcpClient cli = (TcpClient)obj; try { StreamReader reader = new StreamReader(cli.GetStream()); StreamWriter writer = new StreamWriter(cli.GetStream()); String clientInfo = reader.ReadLine(); // citanje info za najaveniot klient Console.WriteLine(clientInfo); int clid = Convert.ToInt32(clientInfo.Split(',')[0]); String pw = clientInfo.Split(',')[1]; int port = ((IPEndPoint)cli.Client.RemoteEndPoint).Port; ClientContainer cc = new ClientContainer(clid, pw, cli.GetStream(), writer); if (!listOfClients.Contains(cc)) { writer.WriteLine("Најавата е успешна."); writer.Flush(); listOfClients.AddLast(cc); Console.WriteLine("Успешно додаден клиент во листата."); while (true) { String poraka; while ((poraka = reader.ReadLine()) == null) { ; } int toId = Convert.ToInt32(poraka); if (IdExists(toId)) { Console.WriteLine("Проверка ID"); writer.WriteLine("ПОСТОИ"); writer.Flush(); String toPwd = reader.ReadLine(); ClientContainer ccon; if ((ccon = PasswordAuthentication(toId, toPwd)) != null) { Console.WriteLine("Проверка Password"); writer.WriteLine("ТОЧЕН"); writer.Flush(); String row; row = reader.ReadLine(); String [] buffer = new String[100]; buffer[0] = row; int i = 1; Console.WriteLine(buffer[0]); while (!(row = reader.ReadLine()).Equals("END")) { buffer[i] = row; //Console.WriteLine(buffer[i]); i++; //Console.WriteLine(i); } Console.WriteLine("#Пренесувам датотека " + buffer[0]); StreamWriter writerTo = ccon.getWriter(); writerTo.WriteLine(buffer[0]); writerTo.Flush(); i = 1; while (i < 100) { writerTo.WriteLine(buffer[i]); i++; } writerTo.WriteLine("END"); writerTo.Flush(); Console.WriteLine("Завршено пренесување"); } else { writer.WriteLine("ГРЕШЕН"); writer.Flush(); } } else { writer.WriteLine("НЕПОСТОИ"); writer.Flush(); } } } else { Console.WriteLine("Додавањето во листа е неуспешно."); writer.WriteLine("Најавата е неуспешна."); writer.Flush(); } } catch { } finally { if (cli != null) { cli.Close(); } } }
/// <summary> /// Método que enviará os comandos a todos os jogadores. /// </summary> /// <param name="text">O texto que será enviado</param> private void send(String text) { writer.Write(text); writer.WriteLine(); writer.Flush(); }
static void Work(TcpClientWrapper client) { while (client.Client.Connected) { string tmp = client.ReadLine(); if (tmp.Contains("Type\":\"user")) //проверка на пользователя { User user = JsonConvert.DeserializeObject <User>(tmp); if (user.NeedDelete) { Message notifMessage = new Message(); notifMessage.Content = $"[{DateTime.Now}][{user.Name}] has left chat\r\n"; string jsonMessage = JsonConvert.SerializeObject(notifMessage, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonMessage); } Console.WriteLine($"[{DateTime.Now}]:{client.Client.Client.RemoteEndPoint.ToString()} left"); client.Client.Client.Close(); allClients.Remove(client); userList.Data.Remove(user); string jsonUsers = JsonConvert.SerializeObject(userList, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonUsers); } } else { StreamReader readId = new StreamReader(path_user_id_file); int get_id = Convert.ToInt32(readId.ReadLine()); readId.Close(); user.Id = get_id; StreamWriter writeId = new StreamWriter(path_user_id_file); writeId.WriteLine(++get_id); writeId.Flush(); writeId.Close(); userList.Data.Add(user); string jsonUsers = JsonConvert.SerializeObject(userList, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonUsers); } Message notifMessage = new Message(); notifMessage.Content = $"[{DateTime.Now}][{user.Name}] has joined chat\r\n"; string jsonMessage = JsonConvert.SerializeObject(notifMessage, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonMessage); } } } else if (tmp.Contains("Type\":\"message")) { Message message = JsonConvert.DeserializeObject <Message>(tmp); string fullMessage = $"[{DateTime.Now}][{message.Sender}]:{message.Content}\r\n"; message.Content = fullMessage; string jsonMessage = JsonConvert.SerializeObject(message, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonMessage); } } } }