/// <summary> /// Handles the ServerLog Event /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void Ftp_ServerLogEvent(object sender, ServerLogArgs args) { ServerLog.Dispatcher.Invoke(new Action(() => { ServerLog.AppendText(args.Message + Environment.NewLine); ServerLog.Focus(); ServerLog.CaretIndex = ServerLog.Text.Length; ServerLog.ScrollToEnd(); })); }
private void WriteMessage(string message) { if (InvokeRequired) { this.Invoke(new Action <string>(WriteMessage), message); } else { if (ServerLog.Text != "") { ServerLog.AppendText(Environment.NewLine); } ServerLog.Select(ServerLog.TextLength, 0); ServerLog.AppendText("Server >> " + message); ServerLog.SelectionStart = ServerLog.TextLength; ServerLog.SelectionLength = 0; ServerLog.ScrollToCaret(); } }
private void ServerListening() { try { Socket listener = new Socket(SocketType.Stream, ProtocolType.Tcp); listener.Bind(new IPEndPoint(IPAddress.Any, serverPort)); listener.Listen(0); serverIsRunning = true; Thread serverProcessingThread = new Thread(ServerProcessing); serverProcessingThread.Start(); while (serverIsRunning) { if (listener.Poll(0, SelectMode.SelectRead)) { Socket socket = listener.Accept(); bool authorizedConnection = false; JObject response = new JObject(); response.Add("result", "error"); string request = ""; //чтение запроса if ((request = ReceiveRequest(socket)).Length > 0) { JObject data = JObject.Parse(request); string action = data.GetValue("action").ToString(); //обработка запроса if (action == "authorization") { //чтение и проверка пароля string name = data.GetValue("name").ToString(); string password = data.GetValue("password").ToString(); if (password.Equals(serverPassword)) { //добавление клиента в очередь Client client = null; if ((client = clients.Find(item => item.Name == name)) == null) { if (clients.Count < maximumClients) { response["result"] = "success"; string text = string.Format("[{0}]: {1} connected", DateTime.Now.ToString("H:m:ss"), name); Invoke((MethodInvoker)(() => { ServerLog.AppendText(text + Environment.NewLine); })); //уведомление других клиентов JObject notification = new JObject(); notification.Add("action", "message"); notification.Add("message", text); for (int j = 0; j < clients.Count; ++j) { SendRequest(clients[j].Socket, notification); } //добавление клиента в очередь clients.Add(new Client(DateTime.Now, socket, name)); authorizedConnection = true; } else { response.Add("message", "Server is full!"); } } else { response.Add("message", "User with this name already exists!"); } } else { response.Add("message", "Invalid password!"); } } else { response.Add("message", "You are not authorized!"); } } //формирование и отправка ответа SendRequest(socket, response); //если поключенный клиент не авторизовался if (!authorizedConnection) { socket.Close(); } } else { Thread.Sleep(sleepTime); } } listener.Close(); while (serverProcessingThread.IsAlive) { Thread.Sleep(sleepTime); } } catch (ThreadAbortException) { } catch (Exception exception) { Invoke((MethodInvoker)(() => { StartServer.Enabled = true; StopServer.Enabled = false; ServerLog.Clear(); })); MessageBox.Show(exception.Message); } }
private void ServerProcessing() { Queue <string> disconnected = new Queue <string>(); while (serverIsRunning) { for (int i = 0; i < clients.Count; ++i) { try { string request = ""; //чтение запроса if ((request = ReceiveRequest(clients[i].Socket)).Length > 0) { JObject data = JObject.Parse(request); string action = data.GetValue("action").ToString(); if (action == "send_message") { string message = data.GetValue("message").ToString(); string text = string.Format("[{0}]: {1}: {2}", DateTime.Now.ToString("H:m:ss"), clients[i].Name, message); Invoke((MethodInvoker)(() => { ServerLog.AppendText(text + Environment.NewLine); })); JObject response = new JObject(); response.Add("action", "message"); response.Add("message", text); for (int j = 0; j < clients.Count; ++j) { SendRequest(clients[j].Socket, response); } } else if (action == "disconnect") { disconnected.Enqueue(clients[i].Name); } } //если клиент долго не отправлял запросов else if ((DateTime.Now - clients[i].LastActivity).TotalSeconds > inactiveTimeout) { disconnected.Enqueue(clients[i].Name); } } catch (Exception) { } } try { //удаление из очереди отключенных клиентов if (disconnected.Count > 0) { while (disconnected.Count > 0) { string name = disconnected.Dequeue(); Client client = clients.Find(item => item.Name == name); //уведомление клиента JObject notification = new JObject(); notification.Add("action", "disconnect"); SendRequest(client.Socket, notification); //удаление клиента clients.RemoveAll(item => item.Name == name); string text = string.Format("[{0}]: {1} disconnected", DateTime.Now.ToString("H:m:ss"), name); Invoke((MethodInvoker)(() => { ServerLog.AppendText(text + Environment.NewLine); })); //уведомление других клиентов notification = new JObject(); notification.Add("action", "message"); notification.Add("message", text); for (int j = 0; j < clients.Count; ++j) { SendRequest(clients[j].Socket, notification); } } } } catch (Exception) { } } //отключение клиентов for (int i = 0; i < clients.Count; ++i) { try { //уведомление клиента JObject notification = new JObject(); notification.Add("action", "disconnect"); SendRequest(clients[i].Socket, notification); clients[i].Socket.Close(); } catch (Exception exception) { MessageBox.Show(exception.Message); } } clients.Clear(); }
public void UpdateServerLog(string message, Color sendercolor) { try { if (ServerLog.InvokeRequired) { Invoke(updateServerLogDelegate, message, sendercolor); } else { ServerLog.SelectionStart = ServerLog.TextLength; ServerLog.SelectionLength = 0; ServerLog.SelectionColor = sendercolor; List <string> messageComponents = new List <string>(); if (message.Contains(':')) { messageComponents.Add(message.Substring(0, message.IndexOf(':') + 1)); messageComponents.Add(message.Substring(message.IndexOf(':') + 1) + "\n"); } else { messageComponents.Add(message + "\n"); } for (int i = 0; i < messageComponents.Count; ++i) { while (messageComponents[i].Contains("<color")) { int startOfTag = messageComponents[i].IndexOf("<color ("); int endOfTag = messageComponents[i].IndexOf(")>"); string colorString = messageComponents[i].Substring(startOfTag + 8, endOfTag - startOfTag - 8); string[] colors = colorString.Split(','); ServerLog.AppendText(messageComponents[i].Substring(0, startOfTag)); if (colors.Length == 3) { int r = 0, g = 0, b = 0; if (Int32.TryParse(colors[0], out r) && Int32.TryParse(colors[1], out g) && Int32.TryParse(colors[2], out b)) { ServerLog.SelectionColor = Color.FromArgb(r, g, b); } } ServerLog.AppendText(messageComponents[i].Substring(endOfTag + 2, messageComponents[i].IndexOf("</color>") - endOfTag - 2)); messageComponents[i] = messageComponents[i].Substring(messageComponents[i].IndexOf("</color>") + 8); ServerLog.SelectionColor = ServerLog.ForeColor; } ServerLog.AppendText(messageComponents[i]); ServerLog.SelectionColor = ServerLog.ForeColor; } ServerLog.SelectionStart = ServerLog.Text.Length; ServerLog.ScrollToCaret(); } } catch (System.InvalidOperationException e) { Console.WriteLine(e.Message); } catch (InvalidAsynchronousStateException e) { Console.WriteLine(e.Message); } }