private static Task StartListener(CancellationToken token) { return(Task.Factory.StartNew(() => { TcpListener listener = new TcpListener(IPAddress.Any, 5555); listener.Start(); while (!token.IsCancellationRequested) { if (listener.Pending()) { TcpClient remoteClient = listener.AcceptTcpClient(); IPEndPoint remoteEndpoint = remoteClient.Client.RemoteEndPoint as IPEndPoint; if (remoteEndpoint != null) { Console.WriteLine($"Message sent from {remoteEndpoint.Address.ToString()}"); Console.Write(">"); string message = default(string); XmlSerializer serializer = new XmlSerializer(typeof(Message)); using (Stream nStream = remoteClient.GetStream()) using (StreamReader sr = new StreamReader(nStream)) { message = sr.ReadToEnd(); } using (UdpClient udpClient = new UdpClient()) { byte[] msgBytes = ASCIIEncoding.ASCII.GetBytes(message); udpClient.Send(msgBytes, msgBytes.Length, new IPEndPoint(IPAddress.Broadcast, 5556)); Console.WriteLine($"Message from {remoteEndpoint.Address.ToString()} broadcasted on port 5556"); Console.Write(">"); } } } } }, token)); }
static void Main(string[] args) { var localAddr = IPAddress.Parse("127.0.0.1"); var port = 13000; List <ClientInfo> clientsList = new List <ClientInfo>(); try { var server = new TcpListener(localAddr, port); server.Start(); Console.WriteLine("--Chat server started--"); while (true) { if (server.Pending()) { var client = server.AcceptTcpClient(); Console.WriteLine("Accept connection from {0}", client.Client.RemoteEndPoint); addUser(ref client, ref clientsList); } else { for (int i = 0; i < clientsList.Count; i++) { if (clientsList[i].Client.Available > 0) { Process(clientsList.IndexOf(clientsList[i]), ref clientsList); } } } Thread.Sleep(100); } } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); }
static void Main(string[] args) { //Server Certificate X509Certificate serverCertificate = new X509Certificate("sslstreamtestcert.pfx", "123456"); //List for each connected client List <ClientConnection> clients = new List <ClientConnection>(); //TCP Listener TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1000); //Start Listening listener.Start(); Console.WriteLine("Started listening"); //flag that specifies if the message variable should be sent bool sendmessage = false; //message variable, the program will add characters to this string until sendmessage is flagged. string message = ""; //multiple ping iterations, the number of pings sent to the other side and the number of pongs to expect int multiping_iterations = 10000; //the number of pongs received while in multiping int multiping_iterations_received = 0; //a flag specifying if a multiping was sent, to avoid receiving messages while multiping is executing. bool multipingsent = false; Stopwatch multiping_stopwatch = new Stopwatch(); while (true) { //if there's a pending connection, initialize it. if (listener.Pending()) { //Accept connection var connection = new ClientConnection { Client = listener.AcceptTcpClient(), Buffer = new MemoryBuffer(ConfigBufferSize) }; Stream stream = connection.Client.GetStream(); //apply encryption if configured if (((bool?)ConfigurationManagerEx.AppSettings["Encryption"]).GetValueOrDefault(false) == true) { stream = new SslStream(stream); ((SslStream)stream).AuthenticateAsServer(serverCertificate, false, SslProtocols.Ssl3, false); } Common.DisplayStreamInformation(stream); //buffer the stream with async read, this is to simplify the understanding of program flow, usually should be done with Async methods stream = new StreamReadAsync(stream); //Apply compression if requested if (((bool?)ConfigurationManagerEx.AppSettings["Compression"]).GetValueOrDefault(false) == true) { stream = new CompressedNetworkStream(stream); } connection.Stream = stream; clients.Add(connection); Console.WriteLine("Client connected"); } //Read message from Console. Common.ReadMessage(ref sendmessage, ref message); //If sendmessage is flagged, send the message if (sendmessage == true) { //if the sendmessage requested is a multiping, send the amount of pings to the other side. if (message == "multiping\r") { multipingsent = true; multiping_iterations_received = 0; multiping_stopwatch.Restart(); for (int i = 0; i < multiping_iterations; i++) { foreach (var client in clients) { Common.SendChatMessage(client.Client, client.Stream, "ping\r"); } } } //send the message, zero it and unflag the sendmessage foreach (var client in clients) { Common.SendChatMessage(client.Client, client.Stream, message); } message = ""; sendmessage = false; //flush the stream buffers. foreach (var client in clients) { client.Stream.Flush(); } } //read data from clients foreach (var client in clients) { if (client.Client.Connected) { client.Stream.CopyTo(client.Buffer); } } //check if full message arrived foreach (var client in clients) { do { ChatMessage chatmessage = null; //read one whole message from the buffer Common.ReadStreamToMessageStream(client.Buffer, out chatmessage); if (chatmessage != null) { //if we're inside multiping, do not display messages if (multipingsent == false) { Console.WriteLine("{0} Received: {1}", DateTime.Now, chatmessage.Message); } //if the message received is ping, send a pong if (chatmessage.Message.Equals("ping\r", StringComparison.InvariantCultureIgnoreCase)) { Common.SendChatMessage(client.Client, client.Stream, "pong\r"); } //if the message received is a pong, add it to the multiping counter, if the requests equals the //response iterations, show how much time it took to receive these messages //BUG: possible bug if multiple clients are connected if (chatmessage.Message.Equals("pong\r", StringComparison.InvariantCultureIgnoreCase)) { multiping_iterations_received++; if (multiping_iterations == multiping_iterations_received) { multipingsent = false; Console.WriteLine("Received {0} pongs in {1}ms.", multiping_iterations_received, multiping_stopwatch.ElapsedMilliseconds); } } } } //while we have messages in the buffer, continue showing messages while (client.Buffer.Length > 0); //flush the buffers (for the replying part). client.Stream.Flush(); } } }
protected void Run() { try { Listener = new TcpListener(localEndPoint); Listener.Start(); } catch (SocketException e) { if (e.Message.Contains("Only one usage of each socket address (protocol/network address/port) is normally permitted")) { Console.WriteLine("ERROR: Socket is in use. Possibly, another server instance is already running. Aborting..."); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); Shutdown(); return; } } Console.WriteLine("[System] Server is running now..."); IsRunning = true; while (IsRunning) { CheckConnections(DisconnectUser); foreach (var user in usersOnline) { try { if (user.Stream.DataAvailable) { Process(user); } } catch (SocketException sockex) { if (sockex.SocketErrorCode == SocketError.NotConnected) { Console.WriteLine($"{user.Name} has been disconnected. [Exception: {sockex.Message}]"); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } } if (Listener.Pending()) { var client = Listener.AcceptTcpClient(); var clientIP = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString(); var clientPort = ((IPEndPoint)client.Client.RemoteEndPoint).Port.ToString(); Console.WriteLine("\n[System] Incoming connection request from {0}:{1}...", clientIP, clientPort); var session = new UserSession(client); usersToAuthorize.Add(session); } foreach (var user in usersToAuthorize) { if (user.Client.Connected) { if (Authorize(user)) { break; } } else { usersToAuthorize.Remove(user); break; } } } Shutdown(); }
static void UserInput() { try { Console.Write(">"); string data = Console.ReadLine(); if (string.IsNullOrEmpty(data)) { UserInput(); } data.Remove(0, 1); string[] dataSplice = data.Split(); switch (dataSplice[0].ToLower()) { case "kick": if (!String.IsNullOrEmpty(dataSplice[1])) { Console.WriteLine($"Nu kickar vi användaren {dataSplice[1]}"); } else { Console.WriteLine("Du måste mata in en användare som du vill kicka"); } break; case "ls": Environment.Exit(0); break; case "stop": foreach (TcpClient c in tcpClients) { c.Dispose(); } listener.Stop(); Console.WriteLine("Servern stoppades"); break; case "start": if (!listener.Pending()) { listener.Start(); Console.WriteLine("Servern startades"); } Console.WriteLine("Servern är redan igång"); break; case "exit": Console.WriteLine("Shutting down"); Environment.Exit(0); break; } } catch { } UserInput(); }
static void Main(string[] args) { TcpListener Listener = new TcpListener(IPAddress.Any, 6667); List <TcpClient> Clients = new List <TcpClient>(); List <String> XMit = new List <String>(); List <String> Users = new List <String>(); Byte[] Buffer; Listener.Start(); while (true) { while (Listener.Pending()) { Clients.Add(Listener.AcceptTcpClient()); } foreach (TcpClient Client in Clients) { if (Client.Available > 0) { Buffer = new Byte[Client.Available]; NetworkStream ClientStream = Client.GetStream(); ClientStream.Read(Buffer, 0, Buffer.Length); XMit.Add(System.Text.Encoding.UTF8.GetString(Buffer)); XMit.Add("START OF WHO LIST 66671208"); foreach (string Username in Users) { XMit.Add("USERS >> " + Username); } String loginOrOut = System.Text.Encoding.UTF8.GetString(Buffer); if (loginOrOut.Contains("has logged")) { if (loginOrOut.Contains(":")) { return; } else { if (loginOrOut.Contains("has logged off.")) { Users.Remove(loginOrOut.Substring(0, loginOrOut.LastIndexOf("has logged") - 1)); } else { Users.Add(loginOrOut.Substring(0, loginOrOut.LastIndexOf("has logged") - 1)); } } } Console.WriteLine("Relaying: " + System.Text.Encoding.UTF8.GetString(Buffer)); } } XMit.RemoveAll((X) => String.IsNullOrWhiteSpace(X)); foreach (TcpClient Client in Clients) { try { NetworkStream ClientStream = Client.GetStream(); foreach (String Line in XMit) { Buffer = System.Text.Encoding.UTF8.GetBytes(Line); ClientStream.Write(Buffer, 0, Buffer.Length); } } catch (IOException) { Console.WriteLine(String.Format("Unable to forward message to client @ {0}, network failure", Client.Client.RemoteEndPoint)); } catch (ObjectDisposedException) { Console.WriteLine(String.Format("Unable to forward message to client @ {0}, stream closed", Client.Client.RemoteEndPoint)); } } XMit.Clear(); Clients.RemoveAll((Client) => !Client.Connected); Thread.Sleep(5); } }