//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Public Packets static bool PublicPacketHandler(Packet p, ClientData client) { Packet response = null; switch (p.PacketType) { case PacketType.SchülerLogin: //DB----- Try Login ClientHandler.Ausgabe("Auth", "Email: " + p.Data["email"] + " Passwort: " + p.Data["passwort"] + " try to login"); DatenbankArgs args = client.db_Manager.Schüler.login(p.Data["email"].ToString(), p.Data["passwort"].ToString()); if (args.Success) { ClientHandler.ClientLogin(client.id); //In liste schreiben //Console.WriteLine(ClientHandler.checkLoginState(client.id)); //Daten speichern client.email = p.Data["email"].ToString(); //email als Erkennungsmerkmal setzen client.name = (string)args.Data.Rows[0]["S_Name"]; client.vname = (string)args.Data.Rows[0]["S_Vorname"]; client.SetAutorKürzel(); ClientHandler.Ausgabe("Auth", client.vname + "." + client.name + "." + client.email + " (Schüler) eingeloggt"); } else { ClientHandler.Ausgabe("Auth", p.Data["email"] + " Login fehlgeschlagen!"); } response = new Packet(PacketType.SchülerLogin, args.Data, args.Success, args.Error); //------ break; case PacketType.LehrerLogin: //DB----- Try Login ClientHandler.Ausgabe("Auth", "Email: " + p.Data["email"] + " Passwort: " + p.Data["passwort"] + " try to login"); args = client.db_Manager.Lehrer.login(p.Data["email"].ToString(), p.Data["passwort"].ToString()); if (args.Success) { ClientHandler.ClientLogin(client.id); //In liste schreiben client.email = p.Data["email"].ToString(); //email als Erkennungsmerkmal setzen client.name = (string)args.Data.Rows[0]["L_Name"]; client.vname = (string)args.Data.Rows[0]["L_Vorname"]; client.SetAutorKürzel(); client.hasRights = true; ClientHandler.Ausgabe("Auth", client.vname + "." + client.name + "." + client.email + " (Lehrer) eingeloggt"); } else { ClientHandler.Ausgabe("Auth", p.Data["email"] + " Login fehlgeschlagen!"); } response = new Packet(PacketType.LehrerLogin, args.Data, args.Success, args.Error); //------ break; case PacketType.SchülerRegistraition: //Register Schüler args = client.db_Manager.Schüler.add(p.Data["name"].ToString(), p.Data["vname"].ToString(), p.Data["phone"].ToString(), p.Data["email"].ToString(), p.Data["klasse"].ToString(), p.Data["passwort"].ToString()); if (args.Success) { ClientHandler.Ausgabe("Auth", p.Data["email"] + " wurde erfolgreich registriert"); } else { ClientHandler.Ausgabe("Auth", p.Data["email"] + " Registrierung fehlgeschlagen!"); } response = new Packet(PacketType.SchülerRegistraition, args.Data, args.Success, args.Error); break; case PacketType.LehrerRegistraition: //Register Lehrer if ((string)p.Data["lehrerPasswort"] != lehrerPasswort) { args = new DatenbankArgs("Lehrer Passwort falsch.\n Versuchen Sie es erneut."); } else { args = client.db_Manager.Lehrer.add(p.Data["vname"].ToString(), p.Data["name"].ToString(), p.Data["anrede"].ToString(), p.Data["email"].ToString(), p.Data["passwort"].ToString(), p.Data["titel"].ToString()); } if (args.Success) { ClientHandler.Ausgabe("Auth", p.Data["email"] + " wurde erfolgreich registriert"); } else { ClientHandler.Ausgabe("Auth", p.Data["email"] + " Registrierung fehlgeschlagen!"); } response = new Packet(PacketType.LehrerRegistraition, args.Data, args.Success, args.Error); break; case PacketType.Klassenwahl: response = Klassenwahl(client); break; } if (response != null) { ClientHandler.SendSinglePacket(client, response); //ClientHandler.Ausgabe("Auth", "Anfrage wurde bearbeitet"); return(true); } return(false); }
private void HandleData(string[] packetData) { //Console.WriteLine($"Got a packet: {packetData[0]}"); switch (packetData[0]) { case "login": if (!AssertPacketData(packetData, 2)) { return; } this.UserName = packetData[1]; Console.WriteLine($"User {this.UserName} is connected"); if (DoctorPasswordData.DoctorPassWords.ContainsKey(this.UserName)) { Console.WriteLine("Username is in use by doctor"); Write("login\r\nerror\r\nThe username is in use"); return; } if (AllClients.TotalClients.ContainsKey(UserName)) { Client client; AllClients.TotalClients.TryGetValue(UserName, out client); if (client.IsOnline) { Write("login\r\nerror\r\nA user with the same name is already online"); } else { Client clientData; AllClients.TotalClients.TryGetValue(this.UserName, out clientData); this.ClientData = clientData.ClientData; AllClients.Remove(this.UserName); Write("login\r\nok"); AllClients.Add(UserName, this); } } else { foreach (Client client in AllClients.TotalClients.Values) { if (client.IsDoctor && client.IsOnline) { client.Write($"AddClient\r\n{UserName}"); } } Write("login\r\nok"); AllClients.Add(UserName, this); } break; case "data": if (!AssertPacketData(packetData, 8)) { return; } this.ClientData.AddData(packetData[1], packetData[2], packetData[3], packetData[4], packetData[5], packetData[6], packetData[7]); Write("data\r\nData Recieved"); this.ClientData.PrintData(); //send real time data to all connected doctors foreach (Client client in AllClients.TotalClients.Values) { if (client.IsDoctor && client.IsOnline) { Console.WriteLine("Data size: " + this.ClientData.Data.Count); string recentDataJson = JsonConvert.SerializeObject(this.ClientData.Data); Console.WriteLine("Sending realtime: " + recentDataJson); client.Write($"RealTimeData\r\n{this.UserName}\r\n{recentDataJson}"); } } break; case "DoctorLogin": Console.WriteLine("DoctorLogin received"); if (!AssertPacketData(packetData, 3)) { return; } string username = packetData[1]; string password = packetData[2]; //check password Dictionary <string, string> passwords = DoctorPasswordData.DoctorPassWords; string dictionaryPassword; if (AllClients.TotalClients.ContainsKey(username)) { Client client; AllClients.TotalClients.TryGetValue(username, out client); if (client.IsOnline) { Write("DoctorLogin\r\nerror\r\nYou are already logged in somewhere else!"); return; } } if (passwords.ContainsKey(username)) { passwords.TryGetValue(username, out dictionaryPassword); if (dictionaryPassword.Equals(password)) { this.UserName = username; Console.WriteLine("correct password"); this.IsDoctor = true; Write("DoctorLogin\r\nok"); if (AllClients.TotalClients.ContainsKey(username)) { AllClients.TotalClients.Remove(username); } AllClients.TotalClients.Add(username, this); this.IsOnline = true; } else { Console.WriteLine("incorrect password"); Write("DoctorLogin\r\nerror\r\nIncorrect password"); } } else { Console.WriteLine("incorrect username"); Write("DoctorLogin\r\nerror\r\nIncorrect username"); } break; case "GetHistoricData": //doctor wants historic data if (!AssertPacketData(packetData, 2) || !this.IsDoctor) { return; } string dataUsername = packetData[1]; Client userClient; bool gotValue = AllClients.TotalClients.TryGetValue(dataUsername, out userClient); if (!gotValue) { Write("GetHistoricData\r\nerror\r\nUsername not found"); } else { //We moeten de graph lijst pakken i.p.v. de getJson!!! string historicDataJson = JsonConvert.SerializeObject(userClient.ClientData.Graphs); Write($"GetHistoricData\r\n{dataUsername}\r\n{historicDataJson}"); } break; case "GetRealtimeData": if (!IsDoctor) { return; } break; case "StartTraining": //Server ontvangt dit en moet dit doorsturen naar bijbehorende Client if (!AssertPacketData(packetData, 2) || !this.IsDoctor) { return; } dataUsername = packetData[1]; gotValue = AllClients.TotalClients.TryGetValue(dataUsername, out userClient); if (!gotValue) { Write("StartTraining\r\nerror\r\nUsername not found"); } else { if (!userClient.IsOnline) { Write("StartTraining\r\nerror\r\nUser not online"); } else { userClient.Write("StartTraining"); Write("StartTraining\r\nok"); userClient.ClientData.StartGraph(); } } break; case "StopTraining": //Server ontvangt dit en moet dit doorsturen naar bijbehorende Client if (!AssertPacketData(packetData, 2) || !this.IsDoctor) { return; } dataUsername = packetData[1]; gotValue = AllClients.TotalClients.TryGetValue(dataUsername, out userClient); if (!gotValue) { Write("StopTraining\r\nerror\r\nUsername not found"); } else { if (!userClient.IsOnline) { Write("StopTraining\r\nerror\r\nUser not online"); } else { userClient.Write("StopTraining"); Write("StopTraining\r\nok"); userClient.ClientData.FinishGraph(); } } break; case "chatToAll": if (!AssertPacketData(packetData, 2)) { return; } if (this.IsDoctor) { string messageToAll = packetData[1]; foreach (Client client in AllClients.TotalClients.Values) { if (client.IsOnline) { client.Write($"chatToAll\r\nmessage\r\n[{this.UserName}]: {messageToAll}"); } } Write($"chatToAll\r\nok"); } else { Write($"chatToAll\r\nerror\r\nOnly doctors can chat to all"); } break; case "directMessage": if (!AssertPacketData(packetData, 3)) { return; } string messageTo = packetData[1]; string message = packetData[2]; Client messageToClient; gotValue = AllClients.TotalClients.TryGetValue(messageTo, out messageToClient); if (gotValue) { if (this.IsDoctor || messageToClient.IsDoctor) { if (messageToClient.IsOnline) { messageToClient.Write($"directMessage\r\nmessage\r\n({this.UserName}): {message}"); Write($"directMessage\r\nok"); } else { Write($"directMessage\r\nerror\r\nTarget client is not online"); } } } else { Write($"directMessage\r\nerror\r\nNeither client is a doctor"); } break; case "GetClients": if (!IsDoctor || !AssertPacketData(packetData, 1)) { return; } string allUsernames = ""; int userAmount = 0; foreach (Client client in AllClients.TotalClients.Values) { if (!client.IsDoctor) { allUsernames += "\r\n" + client.UserName; userAmount++; } } message = $"GetClients\r\nok\r\n{userAmount}{allUsernames}"; Write(message); break; case "SetResistance": if (!AssertPacketData(packetData, 3)) { return; } Client clientResistance; AllClients.TotalClients.TryGetValue(packetData[1], out clientResistance); if (clientResistance == null) { Write("SetResistance\r\nerror\r\nDid not find user"); } else { clientResistance.Write($"SetResistance\r\n{packetData[2]}"); } break; default: Console.WriteLine("Did not understand: " + packetData[0]); break; } }
//Data Manager //gillt für alle verbundenen Clients public static void DataManager(Packet p) { try { //warten bis Packet verarbeitet wird --> Socket bereit Thread.Sleep(100); //---------------- ClientData client = ClientHandler.GetClientByID(p.SenderId); if (client == null) { return; } //Anmeldunsfreie Packete+++++++++++++++++++++++++++++++++++++++++++++++ if (PublicPacketHandler(p, client)) { return; //packet ist bereits bearbeitet } //Anmeldungspflicht+++++++++++++++++++++++++++++++++++++++++++++++++++++ //Console.WriteLine(client.id); //Console.WriteLine(ClientHandler.checkLoginState(client.id)); if (!ClientHandler.checkLoginState(client.id)) { ClientHandler.Send_Error_Message_to_Client(client, "Bitte Anmeldung durchführen!"); return; } //Angemeldet: (gesicherter Bereich) //Console.WriteLine("received " + p.PacketType); switch (p.PacketType) { case PacketType.Default: //zum Testen Thread.Sleep(500); ClientHandler.Ausgabe("Debug", "packet Default received"); ClientHandler.SendSinglePacket(client, p); break; case PacketType.GetGewählteKurse: GetKurse(client); break; case PacketType.GetAlleKurse: Kurswahl(client); break; case PacketType.KursUpdate: UpdateKurse(client, p); break; case PacketType.GetSchülerInKurs: GetSchülerInKurs(client, p); break; case PacketType.GetSchülerInKlasse: GetSchülerInKlasse(client, p); break; case PacketType.GetChat: GetChat(client); break; case PacketType.SendChatNachricht: SendChatNachricht(client, p); break; case PacketType.GetEreignisse: GetEreignisse(client); break; case PacketType.SendEreigniss: SendEreigniss(client, p); break; case PacketType.KlasseErstellen: KlasseErstellen(client, p); break; case PacketType.GetKlasse: getKlasse(client); break; case PacketType.CreateKurs: CreateKurs(client, p); break; case PacketType.GetLehrer: GetLehrer(client); break; case PacketType.DeleteEreignis: DeleteEreignis(client, p); break; case PacketType.EditEreigniss: EditEreigniss(client, p); break; case PacketType.GetLehrerofKurs: GetLehrerofKurs(client, p); break; default: ClientHandler.Send_Error_Message_to_Client(client, "Unerwartetes Packet!!!"); break; } } catch (Exception exc) { ClientHandler.Ausgabe("PacketManager", exc.Message); } }
private static void RemoveClientFromList(ClientData c) { _clients.Remove(c); }
private static void AbortClientThread(ClientData c) { c.clientThread.Abort(); }
public void setClientInfo(String ip, String clientID, ClientData d) { d.ClientID = clientID; d.ClientIP = ip; }
private static void CloseClientConnection(ClientData c) { c.clientSocket.Close(); }
/// <summary> /// 服务端处理客户端信息循环。 /// </summary> protected async void ClientLoop(TcpClient tc) { try { using (NetworkStream stream = tc.GetStream()) using (Timer timer = new Timer((object obj) => { stream.Close(); }, null, Timeout.Infinite, Timeout.Infinite)) { await WriteFrame(stream, new Common.Frames.Information.RequestFrame()).ConfigureAwait(false); timer.Change(Common.Configs.HelloTimeout, Timeout.Infinite); var informationFrame = await ReadFrame(stream).ConfigureAwait(false) as Common.Frames.Information.AnswerFrame; timer.Change(Timeout.Infinite, Timeout.Infinite); if (informationFrame == null) { throw new Exception("Invalid Hello."); } ClientData client = new ClientData(this, tc, informationFrame); try { OnConnect?.Invoke(client); } catch { } try { Heartbeat(stream); while (true) { timer.Change(Common.Configs.HeartbeatInterval * 3, Timeout.Infinite); FrameBase frame = await ReadFrame(stream).ConfigureAwait(false); timer.Change(Timeout.Infinite, Timeout.Infinite); if (Common.Configs.Debug) { Console.WriteLine("R >" + frame.GetType().ToString()); } OnFrame?.Invoke(client, frame); } } catch { } try { OnDisconnect?.Invoke(client); } catch { } } } catch (Exception ex) { if (Common.Configs.Debug) { Console.WriteLine(ex.Message); } } }
public void ListenerThread() { try { IPHostEntry ipHost = Dns.Resolve("192.168.0.8"); IPAddress ipAddr = ipHost.AddressList[0]; tcpClient = new TcpListener(ipAddr, tcpPortNum); udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); tcpClient.Start(); isRunning = true; // db = new DBConnect(this); con = new ConnectHandler(this); checkACK = new CheckACKThread(this, avdPortNum); Dict_Client = new Dictionary <int, ClientData>(); // 클라이언트의 연결 요청 확인 logMSG("info", "TCP 클라이언트 대기중... CloudPhoneTestServer.ListenerThread"); while (isRunning) { clientData = new ClientData(); clientData.AVDPortNum = avdPortNum; while (!tcpClient.Pending()) { if (isRunning == false) { tcpClient.Server.Close(0); tcpClient.Stop(); tcpClient = null; } Thread.Sleep(100); } //logMSG("info", "클라이언트의 요청 발견... CloudPhoneTestServer.ListenerThread"); // logMSG("info", "TCP 클라이언트 통신용 쓰레드 생성 CloudPhoneTestServer new ConnectionHandler"); con.threadListener = this.tcpClient; tcpThread = new Thread(new ThreadStart(con.clientHandler)); tcpThread.Start(); logMSG("info", "tcpThread 시작"); Thread.Sleep(2000); // TCP로 메시지를 받았으면 바로 BackGroundThread 실행(UDP) //logMSG("info", "UDP Thread 실행 준비"); setClientInfo(con.ip, con.clientID, clientData); // DB 에 클라이언트 ID가 있는 지 체크하고 등록한다. //db.CheckClientID(clientData.ClientID); Dict_ClientID.Add(clientData.ClientID, avdPortNum); ACKThread = new Thread(new ThreadStart(checkACK.SendAckToClient)); clientData._TcpThreadClass = con; clientData.TCPThread = tcpThread; clientData._AckThreadClass = checkACK; clientData.ACKThread = ACKThread; Dict_Client.Add(avdPortNum, clientData); ACKThread.Start(); logMSG("info", "ACKThread 시작"); StartAVD(avdPortNum); IPHostEntry _ipHost = Dns.Resolve(clientData.ClientIP); IPAddress _ipAddr = _ipHost.AddressList[0]; IPEndPoint ipep = new IPEndPoint(_ipAddr, udpPortNum); checkBG = new CheckBackGroundThread(this, udpSock, ipep); udpThread = new Thread(new ThreadStart(checkBG.udpCheckbg)); //logMSG("info", "UDP 클라이언트 통신용 쓰레드 생성... CheckBackGroundThread 실행"); udpThread.Start(); logMSG("info", "udpThread 시작"); // ClientData Set Dict_Client[avdPortNum]._UdpThreadClass = checkBG; Dict_Client[avdPortNum].UDPThread = udpThread; Thread.Sleep(300); } } catch (Exception e) { logMSG("error", "ListenerThread : " + e.Message); isRunning = false; isConnected = false; } finally // TCP, UDP 종료 { if (tcpClient != null) { try { // tcpClient.Server.Shutdown(SocketShutdown.Both); } catch (Exception e) { logMSG("error", "tcpClient Shutdown Err : " + e.Message); } finally { tcpClient.Server.Close(0); tcpClient.Stop(); tcpClient = null; } } if (udpSock != null) { // udpSock.Shutdown(SocketShutdown.Both); udpSock.Close(); udpSock = null; } } }
private static void CloseClientConnection(ClientData c) { c.clientSocket.Close(); }
private static void RemoveClientFromList(ClientData c) { clients.Remove(c); }
private static void AbortClientThread(ClientData c) { c.clientThread.Abort(); }
public void ReadDb(string ip, ClientData cli) { //ClientData cli = new ClientData(); try { _con.Open(); var cmd = new SQLiteCommand(_con); cmd.CommandText = "SELECT * FROM Cars WHERE IPAddress = '" + ip + "'"; SQLiteDataReader reader = cmd.ExecuteReader(); reader.Read(); cli.ID = reader.GetInt32(0); cli.TEAM = reader.GetString(1); cli.IP = reader.GetString(2); cli.WEAR = reader.GetInt32(3); } catch (Exception e) { if (DEBUG) MessageBox.Show("Error: " + e.Message); _con.Close(); } _con.Close(); }
//packet senden++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public static void SendSinglePacket(ClientData client, Packet p) { TCP_connection.SendPacket(client.clientSocket, p, new TCP_connection.ExceptionCallback(SocketDisconnectedException)); }
//Error zum Client weiterleiten public static void Send_Error_Message_to_Client(ClientData c, string msg) { Packet p = new Packet(msg); SendSinglePacket(c, p); }
public static ClientData GetClientByID(string id) { ClientData client = lst_clients[GetClientIndexbyID(id)]; return(client); }