public void Run() { _broadcaster = new Broadcaster(); IPAddress ip = IPAddress.Parse(_servername); TcpListener listener = new TcpListener(ip, _port); /* Gør så at serveren kan skrive input*/ Thread serverInputThread = new Thread(HandleInput); serverInputThread.Start(); _running = true; listener.Start(); Console.WriteLine("Skriv \'new\' for at starte en ny auktion."); while (_running) { System.Console.WriteLine("Server klar til bruger"); /* En socket forbinder*/ Socket clientSocket = listener.AcceptSocket(); /* Lav en ny client handler til forbindelsen */ ClientHandler handler = new ClientHandler(clientSocket, _broadcaster); handler.SetAuction(_auction); /* Start det i en ny tråd */ Thread clientThread = new Thread(handler.RunClient); /* Start trådene */ clientThread.Start(); } }
public void StartThread() { IPAddress address = IPAddress.Parse(GetPublicIp()); TcpListener listener = new TcpListener(IPAddress.Any, 56931); listener.Start(); _server.SetLabelText(address.ToString(), "Online", Color.DarkGreen); while (true) { ClientHandler client = new ClientHandler(listener.AcceptTcpClient(), _server); } }
public void AddClient(ClientHandler client) { onlineUsers.Add(client.Username, client); Packet packet = new Packet(); packet.Flag = Flag.AddClient; packet.Data = client.Username; foreach (ClientHandler clientHandler in onlineUsers.Values) { if (client != clientHandler) { clientHandler.send(packet); } } }
public ServerMain() { onlineUsers = new Dictionary<string, ClientHandler>(); currentGames = new Dictionary<string, List<Game>>(); TcpListener listener = new TcpListener(System.Net.IPAddress.Any, 1330); listener.Start(); while (true) { Console.WriteLine("Listening..."); try { TcpClient tcpClient = listener.AcceptTcpClient(); ClientHandler clientHandler = new ClientHandler(tcpClient, this); Console.WriteLine("Client connected."); } catch (Exception) { Console.WriteLine("disconnected? I dunnooooooo"); } } }
private static void AcceptConnections() { Console.WriteLine("Accepting connections"); Console.WriteLine(""); while (IsRunning) { TcpClient IncomingClient; try { IncomingClient = listener.AcceptTcpClient(); ClientHandler handler = new ClientHandler(IncomingClient); handler.ClientHandlerStop += Handler_ClientHandlerStop; handler.ID = count; count++; handler.Start(); Handlers.Add(handler); } catch (SocketException e) { if (e.SocketErrorCode == SocketError.Interrupted) { Console.WriteLine("Quitting..."); } else { Console.WriteLine("Error occured: " + e.ToString()); } } } foreach (ClientHandler ch in Handlers) { ch.Stop(); } }
public void handshakeHandler(ClientHandler client, Packet packet) { HandshakeRequest request = (HandshakeRequest) packet.Data; client.Username = request.Username; Packet rePacket = new Packet(); rePacket.Flag = Flag.HandshakeResponse; HandshakeResponse response = new HandshakeResponse(); if (onlineUsers.ContainsKey(client.Username)) { response.Response = Response.INVALIDLOGIN; Console.WriteLine("Invalid login received"); } else { response.Response = Response.OK; AddClient(client); SendOnlineList(client); Console.WriteLine("Client accepted."); } rePacket.Data = response; client.send(rePacket); }
public virtual byte [] ProcessDataReceived(byte [] data, ClientHandler ch, int len) { return(null); }
//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); } }
public void SetConnectFour(ClientHandler client, Packet packet) { ConnectFour data = packet.Data as ConnectFour; if (data != null) { foreach (Game currentGame in currentGames[client.Username]) { if (currentGame.Players.Contains(data.Opponent)) { if (currentGame is ServerConnectFour) { ((ServerConnectFour) currentGame).Set(client.Username, data); } } } } }
public void SendOnlineList(ClientHandler client) { List<string> users = new List<string>(onlineUsers.Keys); Packet packet = new Packet(); packet.Flag = Flag.OnlineUserList; packet.Data = users; client.send(packet); }
private bool clientExists(ClientHandler scl) { return _clients.Contains(scl); }
public void Enqueue(ClientHandler client) { SyncdQ.Enqueue(client); }
private static void Main(string[] args) { if (args is null) { throw new ArgumentNullException(nameof(args)); } TcpListener server = null; TcpClient clientSocket = null; try { //read from the file X509Certificate2 serverCertificate = new X509Certificate2(_serverCertificateFile, _serverCertificatePassword); // Set the TcpListener on port 43594 at localhost. int port = 43594; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); server = new TcpListener(localAddr, port); //Creates a socket for client communication clientSocket = default; // Start listening for client requests. server.Start(); Console.WriteLine("TcpListener Started."); /* * Read All chatrooms that are serialized or in database here and add them to the list */ Room globalChat = new Room("Daniel", "Global", true); Rooms.Add("Global", globalChat); /* * Enter the listening loop. This will accept a TCP client and then attempt to authenticate the user. * If the user is authenticated, a thread will be created to handle the client communication of the user, * while the loop continues listening for new client connections. */ while (true) { clientSocket = server.AcceptTcpClient(); string clientIP = ((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString(); Console.WriteLine("Incoming client connection from: " + clientIP); SslStream sslStream = new SslStream(clientSocket.GetStream(), false, App_CertificateValidation); Console.WriteLine("Accepted client " + clientSocket.Client.RemoteEndPoint.ToString()); sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Tls12, false); Console.WriteLine("SSL authentication completed."); // Read the username and password of incoming connection. BinaryReader reader = new BinaryReader(sslStream); string userName = reader.ReadString(); string password = reader.ReadString(); string chatRoom = reader.ReadString(); bool authResult = false; string authMessage = string.Empty; //create folder if it doesn't exist Directory.CreateDirectory("./Users"); User user = new User(); if (File.Exists("./Users/" + userName + ".xml")) //load user info if user exists { user = DeSerializeObject <User>("./Users/" + userName + ".xml"); } else //if user does not exist, create one { user.Username = userName; string saltedHashPassword = GenerateKeyHash(password); user.Password = saltedHashPassword; SerializeObject <User>(user, "./Users/" + userName + ".xml"); } if (!ComparePasswords(user.Password, password)) { authResult = false; authMessage = "Your password or username is incorrect."; } else if (Rooms.TryGetValue(chatRoom, out Room r)) { if (r.IsUsedLoggedIn(userName)) { authResult = false; authMessage = "You are already logged in."; } else { authResult = true; } } else { authResult = true; } // send the authentication results back to the client if it failed if (!authResult) { BinaryWriter writer = new BinaryWriter(sslStream); writer.Write(authResult); writer.Write(authMessage); writer.Close(); sslStream.Close(); } else { BinaryWriter writer = new BinaryWriter(sslStream); writer.Write(authResult); writer.Write(authMessage); Console.WriteLine(user.Username + " has connected from: " + clientIP); user.PublicKey = reader.ReadString(); ClientHandler client = new ClientHandler(sslStream, user); client.Start(); } } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. server.Stop(); clientSocket.Close(); } // Placed this read input to stop it from closing immedietely due to exceptions, so we can see what the issue is. Console.WriteLine("\nHit enter to continue..."); Console.Read(); }
static void Main(string[] args) { Console.Write("~"); string input = Convert.ToString(Console.ReadLine()); if (input == "start") { Console.Write("what port would you like the server to be hosted on?: "); try { port = Convert.ToInt32(Console.ReadLine()); } catch (OverflowException) { Console.WriteLine("What in tarnation! that port is not valid! Try another port."); } catch (FormatException) { Console.WriteLine("That isnt a number, mate. Try again"); } Console.Write("Would you like a password?"); string passStr = Convert.ToString(Console.ReadLine()); passStr = passStr.ToLower(); if (passStr == "yes" || passStr == "y") { Console.Write("Please enter the password you would like for your chatroom: "); string password = (Console.ReadLine()); Console.Write("Confirm? [y/n]"); string dec = Convert.ToString(Console.ReadLine()); dec = dec.ToLower(); if (dec == "y") { Console.Write("Confirmed. Now listening on " + port + " with password"); } else { //not confirmed message } } else { Console.Write("What is the IP of this machine? "); string ipIn = Convert.ToString(Console.ReadLine()); IPAddress ipA = Dns.Resolve(ipIn).AddressList[0]; Console.WriteLine("Now listening on port " + port); TcpListener servSock = new TcpListener(ipA, port); TcpClient clientsock = default(TcpClient); int count = 0; servSock.Start(); while ((true)) { count++; clientsock = servSock.AcceptTcpClient(); byte[] bytesFrom = new byte[10025]; string clientData = null; Random rand0 = new Random(); NetworkStream netstr = clientsock.GetStream(); netstr.Read(bytesFrom, 0, bytesFrom.Length); clientData = Encoding.ASCII.GetString(bytesFrom); clientData = clientData.Substring(0, clientData.IndexOf("$")); CL.Clear(); try { CL.Add(clientData, clientsock); } catch { int temp0 = rand0.Next(0, 1111); string temp1 = Convert.ToString(temp0); clientData = clientData + temp1; CL.Add(clientData, clientsock); } transmit(clientData + " Has Arrived \n", clientData, false); ClientHandler client0 = new ClientHandler(); Console.WriteLine(clientData + " Has Arrived "); client0.ClientStart(clientsock, clientData, CL); } } } }
public virtual byte[] ProcessDataReceived( byte [] data, ClientHandler ch, int len ) { return null; }
public void RemoveClient(ClientHandler client) { onlineUsers.Remove(client.Username); //TODO close games of this user. //TODO remove user from dictionaries. Packet packet = new Packet(); packet.Flag = Flag.RemoveClient; packet.Data = client.Username; foreach (ClientHandler clientHandler in onlineUsers.Values) { clientHandler.send(packet); } client.Disconnect(); }
private ClientHandler retrieveConnectedClient(TcpClient cl) { IPEndPoint ip = cl.Client.RemoteEndPoint as IPEndPoint; ClientHandler scl = new ClientHandler() { Ip = ip}; cl.NoDelay = true; scl.Client = cl; return scl; }
private void startClient(ClientHandler cl) { if (cl != null) { ThreadPool.QueueUserWorkItem(new WaitCallback(cl.listen),null); addNewClient(cl); } }
public void SetChat(ClientHandler client, Packet packet) { ChatMessage msg = (ChatMessage) packet.Data; if (msg.Receiver == "BROADCAST") { foreach (ClientHandler clientHandler in onlineUsers.Values) { clientHandler.send(packet); } } else { ClientHandler clientHandler = onlineUsers[msg.Receiver]; clientHandler.send(packet); client.send(packet); } }
private void addNewClient(ClientHandler cl) { if (!_clients.Contains(cl)) _clients.Add(cl); }
public void SetRPSLS(ClientHandler client, Packet packet) { RockPaperScissorsLizardSpock data = packet.Data as RockPaperScissorsLizardSpock; if (data != null) { foreach (Game currentGame in currentGames[client.Username]) { if (currentGame.Players.Contains(data.Opponent)) { if (currentGame is ServerRPSLS) { ((ServerRPSLS) currentGame).Set(client.Username, data); } } } } }
public void removeClient(ClientHandler cl) { // DC the client first ?! _clients.Remove(cl); }
private static void UpdateAll() { Packet contentChanged = new Packet(PacketType.UpdateAll); ClientHandler.SendPacketToAllLoggedInClients(contentChanged); }
/* Subscribe fra listen */ public void Subscribe(ClientHandler client) { _clients.Add(client); }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 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); }
/* Unsubscribe fra listen */ public void Unsubscribe(ClientHandler client) { _clients.Remove(client); }
public void Run() { string received; while (true) { try { byte[] Buffer = new byte[255]; int rec = s.Receive(Buffer, 0, Buffer.Length, 0); Array.Resize(ref Buffer, rec); received = Encoding.Default.GetString(Buffer); Console.WriteLine(received); string[] st = received.Split('#'); string recipient = st[0]; string MsgToSend = st[1]; if (MsgToSend.Equals("logout")) { dSockets.Remove(recipient); this.isloggedin = false; this.s.Close(); break; } if (strr[0].Equals(" ")) { foreach (KeyValuePair <string, ClientHandler> val in dSockets) { ClientHandler mc = (ClientHandler)val.Value; if (!(mc.name.Equals(recipient)) && mc.isloggedin == true) { byte[] sData = Encoding.Default.GetBytes(this.name + " : " + MsgToSend); mc.s.Send(sData, 0, sData.Length, 0); } } } dSockets.TryGetValue(recipient, out kk); foreach (KeyValuePair <string, ClientHandler> val in dSockets) { ClientHandler mc = (ClientHandler)val.Value; for (int i = 0; i < kk.strr.Length; i++) { if (!(mc.name.Equals(recipient)) && mc.isloggedin == true && mc.name.Equals(kk.strr[i])) { byte[] sData = Encoding.Default.GetBytes(this.name + " : " + MsgToSend); mc.s.Send(sData, 0, sData.Length, 0); break; } } } } catch (Exception e) { Console.WriteLine(e.Message); } } }
public void Enqueue(ClientHandler client) { SyncdQ.Enqueue(client) ; }