elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Trabajando con las ramas de git (tercera parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [Source] Servidor multi cliente. C#
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Source] Servidor multi cliente. C#  (Leído 1,664 veces)
nevachana

Desconectado Desconectado

Mensajes: 61


Ver Perfil
[Source] Servidor multi cliente. C#
« en: 28 Octubre 2015, 21:38 pm »

Encontré este "proyecto" que tenía empezado, es un server hecho en c#.
Creo que puede servirle de ayuda a cualquiera que esté interesado en empezar. ( el código es de hace tiempo, puede tener errores y ser sucio ).

Main:

Código
  1. static void Main(string[] args)
  2.        {
  3.            Program p = new Program();
  4.            p.Start();
  5.        }
  6.        public void Start()
  7.        {
  8.            Console.Title = "Server";
  9.            Server s = new Server();
  10.            s.Write(@" _________                                 ");
  11.            s.Write(@"/   _____/ ______________  __ ___________  ");
  12.            s.Write(@"\_____  \_/ __ \_  __ \  \/ // __ \_  __ \ ");
  13.            s.Write(@"/        \  ___/|  | \/\   /\  ___/|  | \/ ");
  14.            s.Write(@"/_______  /\___  >__|    \_/  \___  >__|   ");
  15.            s.Write(@"        \/     \/                 \/       ");
  16.            s.Write(@"               By Nevachana                ");
  17.            s.Write("Starting server [...]");
  18.  
  19.            int startTime = int.Parse(DateTime.Now.Second.ToString());
  20.  
  21.            tcpConexion conexion = new tcpConexion();
  22.            conexion.startServer();
  23.  
  24.            int finalTime = int.Parse(DateTime.Now.Second.ToString()) - startTime;
  25.            s.Write(string.Format("Server started succesfully in: {0} seconds!",finalTime));
  26.        }

TcpConnection:

Código
  1. class tcpConexion
  2.    {
  3.        private TcpClient client;
  4.        private TcpListener listener;
  5.        private Server s = new Server();
  6.        private List<Tuple<TcpClient, int>> clientList = new List<Tuple<TcpClient, int>>();
  7.        public void startServer()
  8.        {
  9.            new Thread(() => this.Listener()).Start();
  10.        }
  11.        private void Listener()
  12.        {
  13.            this.listener = new TcpListener(IPAddress.Any, 3030);
  14.            this.listener.Start();
  15.            while (true)
  16.            {
  17.                this.client = this.listener.AcceptTcpClient();
  18.                handleClient.newClient(this.client);
  19.            }
  20.        }
  21.        public void startReading(TcpClient client, int clientID)
  22.        {
  23.            this.clientList.Add(new Tuple<TcpClient, int>(client, clientID));
  24.            this.s.Write(string.Format("{0} Client has connected!", clientID));
  25.            s.updateConsoleUsers(this.clientList.Count);
  26.            NetworkStream stream = client.GetStream();
  27.            Byte[] buffer = new Byte[client.Available];
  28.            while (client.Connected)
  29.            {
  30.                try
  31.                {//  &#8214;
  32.                    stream.Read(buffer, 0, buffer.Length);
  33.                    this.s.Write(string.Format("client: {0} has sent: {1}", clientID, Encoding.Default.GetString(buffer).IndexOf("@")));
  34.                    handleData(Encoding.Default.GetString(buffer).IndexOf("@").ToString());
  35.                    stream.Flush();
  36.                }
  37.                catch
  38.                {
  39.                    this.clientList.Remove(new Tuple<TcpClient, int>(client, clientID));
  40.                    s.updateConsoleUsers(this.clientList.Count);
  41.                    stream.Flush();
  42.                    stream.Close();
  43.                    client.Close();
  44.                    this.s.Write(string.Format("{0} has disconnected", clientID));
  45.                }
  46.            }
  47.        }
  48.        public void handleData(string packet)
  49.        {
  50.            int packetID = int.Parse(Regex.Split(packet, "&#8214;")[0]);
  51.  
  52.            switch (packetID)
  53.            {
  54.                case 0:
  55.                    Console.WriteLine("packet recibido ^^");
  56.                    break;
  57.            }
  58.        }
  59.    }

Server:

Código
  1. class Server
  2.    {
  3.        public void Write(string txt)
  4.        {
  5.            Console.WriteLine(DateTime.Now.ToString() + " - " + txt);
  6.        }
  7.        public string updateConsoleUsers(int number)
  8.        {
  9.            return Console.Title = "Server - total users Online: " + number.ToString() + " || Last update: " + DateTime.Now.ToString();
  10.        }
  11.    }

HandleClient: ( debería llamarse newClient .. no?  :rolleyes: ).

Código
  1.    class handleClient
  2.    {
  3.        private static int getID;
  4.        private static Random rand = new Random();
  5.        private static tcpConexion conexion = new tcpConexion();
  6.        public static void newClient(TcpClient client)
  7.        {
  8.            getID = rand.Next(10000000, 99999999);
  9.            new Thread(() => conexion.startReading(client, getID)).Start();
  10.        }
  11.    }

Cuando tenga más tiempo intentaré comentarlo todo ^^.


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
[Source CLS] Cls_Files (Multi-Criterio)
Programación Visual Basic
BlackZeroX 7 3,178 Último mensaje 13 Octubre 2010, 20:50 pm
por ssccaann43 ©
Multi conexiones cliente / server en vb.net?
.NET (C#, VB.NET, ASP)
pepitoatak 4 5,023 Último mensaje 25 Abril 2011, 20:55 pm
por neoncyber
Ayuda con Chat Multi Cliente
Programación Visual Basic
Brian1511 4 3,262 Último mensaje 17 Agosto 2012, 19:22 pm
por Brian1511
Chat multi-cliente
Java
4BatPremier 0 3,488 Último mensaje 25 Febrero 2014, 06:50 am
por 4BatPremier
[Source Code] AmongUS.MOD | Multi Cheat
.NET (C#, VB.NET, ASP)
**Aincrad** 4 5,193 Último mensaje 9 Febrero 2021, 09:00 am
por Mr. NoBody
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines