public void Worker() { while (true) { try { var serverStream = new NamedPipeServerStream("YetAnotherRelogger", PipeDirection.InOut, 100, PipeTransmissionMode.Message, PipeOptions.Asynchronous); serverStream.WaitForConnection(); ThreadPool.QueueUserWorkItem(state => { using (var pipeClientConnection = (NamedPipeServerStream)state) { var handleClient = new HandleClient(pipeClientConnection); handleClient.Start(); } }, serverStream); } catch (Exception ex) { Logger.Instance.WriteGlobal(ex.Message); } Thread.Sleep(Program.Sleeptime); } }
private void InitSocket() { log.logView += "Server1 Start...\n"; server = new TcpListener(IPAddress.Any, 9991); this.stopMachinery += server.Stop; clientSocket = default(TcpClient); server.Start(); log.logView += "Server1 opened successfully\n"; while (true) { try { log.logView += "Server1 is waiting for clients...\n"; clientSocket = server.AcceptTcpClient(); // client 소켓 접속 허용 NetworkStream stream = clientSocket.GetStream(); byte[] buffer = new byte[1024]; // 버퍼 int bytes = stream.Read(buffer, 0, buffer.Length); string user_name = Encoding.Unicode.GetString(buffer, 0, bytes); user_name = user_name.Substring(0, user_name.IndexOf("$")); // client 사용자 명 clientList.Add(clientSocket, user_name); // cleint 리스트에 추가 log.logView += (user_name + " is accepted.\n"); HandleClient h_client = new HandleClient(); // 클라이언트 추가 h_client.OnReceived += new HandleClient.MessageDisplayHandler(OnReceived); h_client.OnDisconnected += new HandleClient.DisconnectedHandler(h_client_OnDisconnected); h_client.OnSent += new HandleClient.SendJsonHandler(OnSent); h_client.OnSentLoginInfo += new HandleClient.SendLoginJsonHandler(OnSentLoginInfo); h_client.startClient(clientSocket, clientList); } catch (SocketException se) { break; }catch (Exception ex) { break; } } if (clientSocket != null) { clientSocket.Close(); // client 소켓 닫기 } log.logView += "Server1 closed\n"; }
/// <summary> /// 等待客戶端的連線 /// </summary> public void ListenToConnection() { //取得本機名稱 string hostName = Dns.GetHostName(); Debug.Log("伺服器名稱=" + hostName); //取得本機IP IPAddress[] ipa = Dns.GetHostAddresses(hostName); for (int i = 0; i < ipa.Length; i++) { Debug.Log("伺服器IP[" + i + "]=" + ipa[i].ToString()); } //建立本機端的IPEndPoint物件 IPEndPoint ipe = new IPEndPoint(ipa[0], 1234); //建立TcpListener物件 TcpListener tcpListener = new TcpListener(ipe); //開始監聽port tcpListener.Start(); Debug.Log("伺服器等待客戶端連線中..."); TcpClient tmpTcpClient; int numberOfClients = 0; while (true) { try { //建立與客戶端的連線 tmpTcpClient = tcpListener.AcceptTcpClient(); if (tmpTcpClient.Connected) { Debug.Log("伺服器與客戶端連線成功!"); HandleClient handleClient = new HandleClient(tmpTcpClient); Thread myThread = new Thread(new ThreadStart(handleClient.Communicate)); numberOfClients += 1; myThread.IsBackground = true; myThread.Start(); myThread.Name = tmpTcpClient.Client.RemoteEndPoint.ToString(); } } catch (Exception ex) { Debug.Log(ex.Message); } } // end while }
static void Main(string[] args) { TcpListener serverSocket = new TcpListener(IPAddress.Any, 20000); int counter = 0; serverSocket.Start(); Console.WriteLine(" >> Server Started"); while (true) { counter += 1; var clientSocket = serverSocket.AcceptTcpClient(); Console.WriteLine(" >> Client No: " + counter + " Started!"); HandleClient client = new HandleClient(); client.StartClient(clientSocket); } }
public void Worker() { while (true) { try { var serverStream = new NamedPipeServerStream("YetAnotherRelogger", PipeDirection.InOut, 254); serverStream.WaitForConnection(); var handleClient = new HandleClient(serverStream); new Thread(handleClient.Start).Start(); } catch (Exception ex) { Logger.Instance.WriteGlobal(ex.Message); } } }
private void runServer() { while (true) { try { serverSocket = new TcpListener(IPAddress.Any, port); TcpClient clientSocket = default(TcpClient); int counter = 0; try { serverSocket.Start(); running = true; } catch { running = false; return; } counter = 0; while (running) { try { counter += 1; clientSocket = serverSocket.AcceptTcpClient(); //Logging.log("Client No:" + Convert.ToString(counter) + " started!", LogPrior.Importand); HandleClient client = new HandleClient(); this.clients.Add(client); client.startClient(this, clientSocket, Convert.ToString(counter)); } catch { } } if (clientSocket != null) { clientSocket.Close(); } if (serverSocket != null) { serverSocket.Stop(); } } catch (Exception ex) { Logging.logException(string.Format("Cannot open server on port {0}", port), ex); } } }
public MainWindow(Model m, HandleClient hc, Login l) { InitializeComponent(); operationIsRun = false; this.login = l; this.hc = hc; this.m = m; timerCont = 0; backupNotFound = false; snapshotNotEmpty = false; path = m.getBackupPath(); currentPath.Add(path); previousVersion = new List <string>(); SnapshotLabel.Text = "Last snapshot"; DeletedListLabel.Text = "List of deleted files"; SetTimer(); //for monitoring changes in the model populatelist(path); }
public void Worker() { while (true) { try { var serverStream = new NamedPipeServerStream("YetAnotherRelogger", PipeDirection.InOut, 254); serverStream.WaitForConnection(); var handleClient = new HandleClient(serverStream); new Thread(handleClient.Start).Start(); } catch (Exception ex) { StatFailed++; DebugHelper.Exception(ex); } } }
/// <summary> /// Glowna funkcja. /// </summary> /// <param name="args"></param> static void Main(string[] args) { try { _localAddr = IPAddress.Parse(GetIpAddress()); //_localAddr = IPAddress.Parse("127.0.0.1"); _port = 8888; _serverListener = new TcpListener(_localAddr, _port); _serverListener.Start(); Console.WriteLine(" >> " + "Server Started"); Console.WriteLine("The local End point is: " + _serverListener.LocalEndpoint); while (true) { if (_clientSockets.Count < 2) { TcpClient _clientSocketNew = _serverListener.AcceptTcpClient(); //zwarca obiekt klasy TcpClient //odpowiada za gniazdo klienckie SearchAvailableId(); DataClients data = new DataClients(_currentId, _clientSocketNew); _clientSockets.Add(data); int lastId = _currentId; _currentId = 1; HandleClient client = new HandleClient(); client.StartClient(_clientSocketNew, lastId); } else { Console.WriteLine("Server is full!!!"); throw new SocketException(); } } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { _serverListener.Stop(); } }
static void Main(string[] args) { TcpListener serverSocket = new TcpListener(10_000); TcpClient clientSocket = default(TcpClient); int counter = 0; serverSocket.Start(); Console.WriteLine("Chat Server started ....."); counter = 0; while ((true)) { counter += 1; clientSocket = serverSocket.AcceptTcpClient(); //byte[] bytesFrom = new byte[10025]; string dataFromClient = null; NetworkStream networkStream = clientSocket.GetStream(); int test = clientSocket.ReceiveBufferSize; byte[] bytesFrom = new byte[test]; networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize); dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom); dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$")); clientList.Add(dataFromClient, clientSocket); Broadcast(dataFromClient + " Joined ", dataFromClient, false); Console.WriteLine(dataFromClient + " Joined chat room "); HandleClient client = new HandleClient(); client.StartClient(clientSocket, dataFromClient, clientList); } clientSocket.Close(); serverSocket.Stop(); Console.WriteLine("exit"); Console.ReadKey(); }
/// <summary> /// Start running the server to listen for connections /// </summary> public static void RunServer() { // Thread safe dictionary to hold the active clients // Thread safe dictionary must be used because the clients may access it // on different threads var clients = new ConcurrentDictionary <long, HandleClient>(); long counter = 0; try { // Start listening // SSL encryption can be added later to improve security // We can also add some logic to limit the number of connections if required var serverSocket = new TcpListener(IPAddress.Any, Port); var clientSocket = default(TcpClient); serverSocket.Start(); // Stop listening if the token is triggered StopServerToken.Token.Register(() => serverSocket.Stop()); Console.WriteLine($"{nameof(Server)} started"); while (true) { // Wait for client to connect clientSocket = serverSocket.AcceptTcpClient(); counter++; Console.WriteLine($"{nameof(Server)} connected to Client {counter}"); // The constructor is asynchronous. This will not block and we can handle more incoming connections clients[counter] = new HandleClient(clients, clientSocket, counter); } } catch (Exception ex) { // Only display the error message if the cancellation token wasn't triggered Console.WriteLine(StopServerToken.IsCancellationRequested ? $"{nameof(Server)} disconnected" : $"Error: {ex.Message}"); } }
public static void ListenToNewClients() { //IPHostEntry host = Dns.GetHostEntry("localhost"); //IPAddress ipAddress = host.AddressList[0]; TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), 11000); serverSocket.Start(); Console.WriteLine(" >> Server Started"); int counter = 0; while (true) { counter += 1; TcpClient clientSocket = serverSocket.AcceptTcpClient(); Console.WriteLine(" >> Client No:" + Convert.ToString(counter) + " started!"); HandleClient handleClient = new HandleClient(); handleClientList.Add(handleClient); handleClient.StartClient(clientSocket, Convert.ToString(counter)); } }
/// <summary> /// Entry Point /// Opens a server, starts the admin thread, and handles client connections /// </summary> private static void Main() { //Connection information var ip = System.Net.IPAddress.Loopback; var serverSocket = new TcpListener(ip, 8888); var clientSocket = default(TcpClient); serverSocket.Start(); Console.WriteLine(" >> " + "Server Started"); var adminThread = new Thread(AdminLoop); adminThread.Start(); while (!Office.Open) { //Wait for sales to open } //Continually loop and wait for client connections while (Office.Open) { if (!serverSocket.Pending()) { continue; } clientSocket = serverSocket.AcceptTcpClient(); var client = new HandleClient(); client.StartClient(clientSocket); } //Manage resources and wrap up Console.WriteLine("Waiting for all clients to disconnect..."); adminThread.Join(); clientSocket?.Close(); serverSocket.Stop(); Console.WriteLine(" >> " + "exit"); }
internal StreamList(HandleClient owner) { this.owner = owner; }
static void Main(string[] args) { TcpListener serverSocket = new TcpListener(IPAddress.Any, 9000); TcpClient clientSocket = default(TcpClient); int counter = 0; try { serverSocket.Start(); Console.WriteLine("GPS Tracker Server Started ...."); while (true) { counter += 1; clientSocket = serverSocket.AcceptTcpClient(); Console.WriteLine("Connected"); byte[] bytesFrom = new byte[10025]; string dataFromClient = null; NetworkStream networkStream = clientSocket.GetStream(); networkStream.Read(bytesFrom, 0, 10025); dataFromClient = Encoding.ASCII.GetString(bytesFrom); //Console.WriteLine("GPS data is: " + dataFromClient); //System.IO.File.WriteAllText(@"C:\_djivanovic\trackerdata.txt", dataFromClient); int contentParseLength = dataFromClient.Split(',').Length; String[] contentParse = dataFromClient.Split(','); String prepare = contentParse.ElementAtOrDefault(1); String imei = null; if (prepare != null) { String[] prepareImei = prepare.Split(':'); imei = prepareImei.ElementAtOrDefault(1); } if (imei != null && !clientsList.Contains(imei)) { clientsList.Add(imei, clientSocket); } else { Console.WriteLine("Assign new socket for client"); clientsList[imei] = clientSocket; continue; } if (contentParseLength == 3 && imei != null) { Broadcast.BroadcastClientData("LOAD", imei, false, clientsList); } //else //{ // continue; //} //broadcast(dataFromClient + " Joined ", dataFromClient, false); Console.WriteLine(imei + " Joined GPS tracker "); HandleClient client = new HandleClient(); client.StartClient(clientSocket, imei, clientsList, dataFromClient); } } catch (Exception e) { Console.WriteLine("Exception is: " + e.Message); } finally { clientSocket.Close(); serverSocket.Stop(); Console.WriteLine("exit"); Console.ReadLine(); } }
internal String connect(string username, string password, string operation) { try { try { networkManager = new NetworkManager(); TcpClient clientSocket = new TcpClient(); string returnString = String.Empty; string status = OpenConnection(networkManager, clientSocket, returnString, operation); if (status != Program._200_OK) { return(status); } switch (operation) { case Program.LOGIN: status = handleLogin(networkManager, clientSocket, returnString, username, password); if (status != Program._200_OK) { return(status); } break; case Program.REGISTRATION: status = handleRegistration(networkManager, clientSocket, returnString, username, password); if (status != Program._200_OK) { return(status); } break; default: Model.PrintHandshakeMessage("Wrong message sended"); if (networkStream != null) { networkStream.Flush(); clientSocket.Close(); } return(Program.LOGINERROR); } client = new HandleClient(clientSocket, networkStream, networkManager, backupPath); client.doHandshake(); return(Program.LOGINTRUE); } catch (IOException e) { Console.WriteLine("client:Exception >> IOException: " + e.Message); throw; } catch (ArgumentOutOfRangeException e) { Console.WriteLine("client:Exception >> ArgumentOutOfRangeException: " + e.Message); throw; } catch (ArgumentNullException e) { Console.WriteLine("client:Exception >> ArgumentNullException: " + e.Message); throw; } catch (FormatException e) { Console.WriteLine("client:Exception >> FormatException: " + e.Message); throw; } catch (InvalidOperationException e) { Console.WriteLine("client:Exception >> InvalidOperationException: " + e.Message); throw; } catch (SocketException e) { Console.WriteLine("client:Exception >> SocketException: " + e.Message); throw; } catch (Exception e) { Console.WriteLine("client:Exception >> Execution terminated because of exception: " + e.Message); throw; } } catch (Exception e) { Console.WriteLine("An error occured during the communication with the server, Closing the network Stream"); //close the connection and alert the view if (networkStream != null) { if (networkStream != null) { networkStream.Flush(); networkStream.Close(); } } return(Program.LOGINERROR); } }
public void OneTimeSetUp() { _handleClient = new HandleClient(); }
private void startServer() { IPAddress ipAd = IPAddress.Parse(this.compIPAddress.Text); try { // use local m/c IP address, and // use the same in the client /* Initializes the Listener */ tcpListener = new TcpListener(ipAd, Convert.ToInt32(this.portNumber.Text)); /* Start Listeneting at the specified port */ tcpListener.Start(); } catch (SocketException soEx) { MessageBox.Show("Error...\n Socket: " + this.portNumber.Text + " of IP address: " + ipAd + " could not be opened."); Console.Write("Error..... " + soEx.StackTrace); tcpListener.Stop(); tcpListener = null; updateGUI(true); return; } int clientCounter = 0; try { AppendToTextBox("Ready....." + "\n"); while (this.continueListening && serverThread.IsAlive) { //if (NaoConnected) // Comment this line for debugging purposes { clientCounter = clientCounter + 1; TcpClient clientSocket = tcpListener.AcceptTcpClient(); HandleClient client = new HandleClient(); client.startClient(clientSocket, this, clientCounter); } } tcpListener.Stop(); } catch (Exception ex) { Console.Write("Error..... " + ex.StackTrace); } }
public void Setup() { _handleClient = new HandleClient(); }
private void serverThread() { #if DEBUG TcpListener serverSocket = new TcpListener(6969); #else TcpListener serverSocket = new TcpListener(6969); #endif TcpClient clientSocket = default(TcpClient); //ClientSocket serverSocket.Start(); Console.Write(" >> " + "Server Started"); int counter = 0; while (true) { try { counter += 1; clientSocket = serverSocket.AcceptTcpClient(); string IPAddress = ((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString(); Console.WriteLine("IPAddress: " + IPAddress); if (IPAddress != "127.0.0.1" && IPAddress != "109.199.125.101") { bool found = false; AntiSpam antispam = new AntiSpam(); foreach (AntiSpam cachedconnection in new List <AntiSpam>(Connections)) { if (cachedconnection.IP == IPAddress) { found = true; antispam = cachedconnection; } } if (found) { Console.WriteLine("IP Found -> " + antispam.Attempts + " IP= " + antispam.IP); if (antispam.Attempts > ConnectionsMax) { //Check if it exceeds double the connections max if (antispam.Attempts == (ConnectionsMax * 2)) { Console.WriteLine("Blocking IP"); INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); INetFwRule firewallRule = firewallPolicy.Rules.OfType <INetFwRule>().Where(x => x.Name == "Blocked: " + IPAddress).FirstOrDefault(); if (firewallRule == null) { firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); firewallRule.Name = "Blocked: " + IPAddress; firewallRule.Description = "Blocking Traffic"; firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; firewallRule.LocalPorts = "6969"; firewallRule.RemoteAddresses = IPAddress; firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; firewallRule.Enabled = true; firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; firewallPolicy.Rules.Add(firewallRule); } Log.WriteLine("Blocked IP (Connection Quota) [" + IPAddress + "]", "Blocked"); } foreach (AntiSpam cachedconnection in new List <AntiSpam>(Connections)) { if (cachedconnection.IP == antispam.IP) { cachedconnection.Attempts = cachedconnection.Attempts + 1; cachedconnection.Attempted = DateTime.Now; } } Console.WriteLine("Blocked Connection {0} Times -> " + IPAddress, antispam.Attempts); clientSocket.NoDelay = true; NetworkStream networkStream = clientSocket.GetStream(); //Byte Streams byte[] outStream = Encoding.ASCII.GetBytes("Connection Quota Reached"); byte[] outSize = BitConverter.GetBytes(outStream.Length); //Network Streams networkStream.Write(outSize, 0, outSize.Length); networkStream.Write(outStream, 0, outStream.Length); networkStream.Flush(); Console.Write(">> Size=" + BitConverter.ToInt32(outSize, 0) + " Response: Connection Quota Reached"); clientSocket.Close(); continue; } else { foreach (AntiSpam cachedconnection in new List <AntiSpam>(Connections)) { if (cachedconnection.IP == antispam.IP) { cachedconnection.Attempts = cachedconnection.Attempts + 1; cachedconnection.Attempted = DateTime.Now; } } } } else { Console.WriteLine("IP Not Found (Adding IP) -> IP= " + IPAddress); Connections.Add(new AntiSpam(IPAddress, 1, DateTime.Now)); } } clientSocket.NoDelay = true; clientSocket.ReceiveTimeout = (60000 * 5); Console.Write(" >> " + "Client No:" + Convert.ToString(counter) + " started!"); Connection connection = new Connection(counter, clientSocket); HandleClient client = new HandleClient(); client.startClient(connection); lock (TcpClients) { TcpClients.Add(connection); } Log.WriteLine("Client Connected [" + IPAddress + "]", "Connections"); } catch (Exception ex) { Log.WriteLine("Client Connection Failed", "DEBUG"); Log.WriteLine(ex.ToString(), "DEBUG"); } } clientSocket.Close(); serverSocket.Stop(); Console.Write(" >> " + "exit"); Console.ReadLine(); }