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

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  CODIGO FUENTE DE UN CHAT CON SOCKETS
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: CODIGO FUENTE DE UN CHAT CON SOCKETS  (Leído 6,614 veces)
syst

Desconectado Desconectado

Mensajes: 2


Ver Perfil
CODIGO FUENTE DE UN CHAT CON SOCKETS
« en: 8 Junio 2012, 12:15 pm »

Hola a todos! Me animo a poner un programa que he hecho estando en prácticas de una FP y bueno, quiero que me digan la porquería que sobra, y, también, mejores formas de hacer lo que yo hice.
Sólo lo he probado en local, no se si funcionaría fuera. Ya lo probaré. De momento con que me digan que mejorar y que sobra, me vale.

Clase Cliente:
Código
  1. 'Chat V1.0.
  2. 'Formulario cliente.
  3. 'Creado por Alejandro Cuenca.
  4. 'El código se puede usar, reutilizar o lo que consideren, aunque es el primero
  5. 'que hago y valdrá de poco. Recuerden agradecer, sólo eso.
  6.  
  7. Imports System.IO
  8. Imports System.Net.Sockets
  9. Imports System.Threading
  10. Imports System.Text
  11.  
  12. Public Class Cliente
  13.  
  14. #Region "VARIABLES"
  15.    Dim TCPCli As TcpClient 'Puerto e IP de conexion al servidor.
  16.    Dim thread As Thread 'Para recibir mensajes del servidor.
  17.    Dim stm As NetworkStream 'Datos que recibo del servidor.
  18.    Dim bufferLectura() As Byte 'Donde guardare los mensajes recibidos del servidor.
  19. #End Region
  20.  
  21. #Region "BOTONES"
  22.    Private Sub btnConectar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConectar.Click
  23.        'Me conecto al servidor.
  24.        TCPCli = New TcpClient
  25.        'Envio un mensaje con el nick.
  26.        'Dim bufferEscritura() As Byte
  27.        Try
  28.            'Me conecto al servidor con IP y Puerto.
  29.            TCPCli.Connect(txtIP.Text, CType(txtPort.Text, Integer))
  30.            'Inicializo el array.
  31.            'bufferEscritura = New Byte(100) {}
  32.            'Si se ha conectado lo muestro, y si no, tambien.
  33.            If TCPCli.Connected = True Then
  34.                'Con getStream obtengo la red en la que estoy.
  35.                stm = TCPCli.GetStream
  36.                'Escribo en el RichTextBox.
  37.                rtbConversacion.Text = rtbConversacion.Text & "Conexion realizada. Conectado a " & txtIP.Text & "." & vbCrLf
  38.                'Mando el nick.
  39.                Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes(txtNick.Text + "$")
  40.                stm.Write(outStream, 0, outStream.Length)
  41.                stm.Flush()
  42.                'Inicio un thread llamando al metodo recibirMensaje para escuchar lo que llega del servidor y mostrarlo.
  43.                thread = New Thread(AddressOf recibirMensaje)
  44.                thread.Start()
  45.                'Activo los controles para enviar mensajes.
  46.                txtTexto.Enabled = True
  47.                btnEnviar.Enabled = True
  48.                rtbConversacion.Enabled = True
  49.            Else
  50.                rtbConversacion.Text = rtbConversacion.Text & "Conexion fallida." & vbCrLf
  51.            End If
  52.        Catch ex As Exception
  53.            rtbConversacion.Text = rtbConversacion.Text & "Error en la conexion" & vbCrLf
  54.        End Try
  55.  
  56.    End Sub
  57.  
  58.    Private Sub btnEnviar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEnviar.Click
  59.        'Defino el array de bytes para enviar el mensaje al servidor.
  60.        Dim bufferEscritura() As Byte
  61.        Dim aux As Boolean = True
  62.        While aux
  63.            Try
  64.                bufferEscritura = New Byte(10000) {}
  65.                'Si el texto empieza por '.', salgo del programa.
  66.                If txtTexto.Text = "." Then
  67.                    terminarConexion()
  68.                Else
  69.                    'Lo codifico para enviarlo.
  70.                    bufferEscritura = Encoding.ASCII.GetBytes(txtTexto.Text)
  71.                    'Escribo en el RichTextBox el mensaje que acabo de enviar.
  72.                    rtbConversacion.Text = rtbConversacion.Text & Chr(13) & "Usted dice: " & Encoding.ASCII.GetString(bufferEscritura) & Chr(13)
  73.                    stm.Write(bufferEscritura, 0, bufferEscritura.Length)
  74.                    'Me situo al final del RichTextBox
  75.                    rtbConversacion.SelectionStart = rtbConversacion.TextLength
  76.                    rtbConversacion.ScrollToCaret()
  77.                    txtTexto.Text = ""
  78.                    txtTexto.Focus()
  79.                End If
  80.            Catch ex As Exception
  81.                rtbConversacion.Text = rtbConversacion.Text & "Error al enviar datos" & vbCrLf
  82.            End Try
  83.            aux = False
  84.        End While
  85.    End Sub
  86.  
  87. #End Region
  88.  
  89. #Region "METODOS"
  90.    Private Sub recibirMensaje()
  91.        While True
  92.            Try
  93.                bufferLectura = New Byte(10000) {}
  94.                stm = TCPCli.GetStream
  95.                'Me quedo esperando a que llegue algun mensaje, y lo leo.
  96.                stm.Read(bufferLectura, 0, bufferLectura.Length)
  97.                escribir()
  98.            Catch ex As Exception
  99.                Exit Sub
  100.            End Try
  101.        End While
  102.    End Sub
  103.  
  104.    Private Sub terminarConexion()
  105.        Me.Close()
  106.    End Sub
  107.  
  108.    Private Sub txtTexto_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTexto.KeyPress
  109.        If e.KeyChar = Chr(13) Then
  110.            e.Handled = True
  111.        Else
  112.            e.Handled = False
  113.        End If
  114.    End Sub
  115.  
  116.    Private Sub escribir()
  117.        'Variables para dividir el mensaje entre el nick y el mensaje.
  118.        Dim men As String
  119.        Dim nom As String
  120.        Dim todo As String
  121.        If Me.InvokeRequired Then
  122.            Me.Invoke(New MethodInvoker(AddressOf escribir))
  123.        Else
  124.            Try
  125.                'Obtengo el mensaje enviado con todos los datos.
  126.                todo = Encoding.ASCII.GetString(bufferLectura)
  127.                'Si es un '.', es que el nick ya se ha elegido.
  128.                If todo.Substring(0, todo.LastIndexOf(Chr(46)) + 1) = "." Then
  129.                    txtNick.Text = ""
  130.                    rtbConversacion.Text = rtbConversacion.Text & Chr(13) & "El nick ya existe, elija otro." & Chr(13)
  131.                Else
  132.                    'Si no es un punto, divido el mensaje en texto y remitente.
  133.                    men = todo.Substring(todo.IndexOf(Chr(93)) + 1, todo.LastIndexOf(Chr(91)) + 1)
  134.                    nom = todo.Substring(0, todo.IndexOf(Chr(93)))
  135.                    'Escribo en el RichTextBox el mensaje reenviado del servidor.
  136.                    rtbConversacion.Text = rtbConversacion.Text & Chr(13) & nom & " dice: " & men & Chr(13)
  137.                End If
  138.            Catch ex As Exception
  139.                'Si no puede asignar nom a nada, es porque el mensaje es del servidor.
  140.                rtbConversacion.Text = rtbConversacion.Text & Chr(13) & "Servidor dice: " & todo & Chr(13)
  141.            End Try
  142.        End If
  143.    End Sub
  144.  
  145.    Private Sub Cliente_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
  146.        'Declare an array of processes
  147.        Dim myProcesses() As Process
  148.        'single process variable
  149.        Dim myProcess As Process
  150.        'Get the list of processes
  151.        myProcesses = Process.GetProcesses()
  152.        'Iterate through the process array
  153.        For Each myProcess In myProcesses
  154.            If myProcess.ProcessName = "TCPCient" Then
  155.                myProcess.Kill()
  156.            End If
  157.        Next
  158.    End Sub
  159. #End Region
  160.  
  161. End Class

Clase servidor:
Código
  1. 'Chat V1.0.
  2. 'Formulario servidor.
  3. 'Creado por Alejandro Cuenca.
  4. 'El código se puede usar, reutilizar o lo que consideren, aunque es el primero
  5. 'que hago y valdrá de poco. Recuerden agradecer, sólo eso.
  6.  
  7.  
  8. Imports System.IO
  9. Imports System.Net.Sockets
  10. Imports System.Threading
  11. Imports System.Text
  12.  
  13. Public Class Servidor
  14.  
  15. #Region "VARIABLES"
  16.    Dim clientSocket As TcpClient
  17.    Dim tcpLis As TcpListener 'Creamos el listener para oir un puerto determinado.
  18.    Dim clientes As New Hashtable 'Creamos una coleccion con los clientes que se conectan.
  19.    Dim thread As Thread 'Creamos un thread para recibir mensajes de los clientes.
  20.    Dim clienteActual As Net.IPEndPoint 'Guardamos la informacion de un cliente para abrir o cerrar la conexion.
  21.    Dim cli As infoCliente 'Guardamos el cliente actual.
  22. #End Region
  23.  
  24. #Region "ESTRUCTURAS"
  25.    Private Structure infoCliente
  26.        Public sock As Socket 'Socket utilizado para mantener la conexion con el cliente
  27.        Public thre As Thread 'Thread utilizado para escuchar al cliente
  28.        Public ultimosDatos As String 'Ultimos datos enviados por el cliente
  29.        Public nombre As String 'Nombre utilizado en el server.
  30.    End Structure
  31. #End Region
  32.  
  33. #Region "METODOS"
  34.    Private Sub esperarCliente()
  35.        Dim infoClienteActual As infoCliente = Nothing
  36.        Dim bufferLectura() As Byte
  37.        With infoClienteActual
  38.            While True
  39.                clientSocket = tcpLis.AcceptTcpClient
  40.                'Cuando se recibe la conexion, guardo la informacion del cliente.
  41.                bufferLectura = New Byte(10000) {}
  42.                'El socket.
  43.                .sock = clientSocket.Client
  44.                clienteActual = .sock.RemoteEndPoint 'Aqui guardamos su EndPoint, que sera la clave del hashtable.
  45.                'Obtenemos el nick.
  46.                Dim networkStream As NetworkStream = clientSocket.GetStream()
  47.                networkStream.Read(bufferLectura, 0, CInt(clientSocket.ReceiveBufferSize))
  48.                .nombre = System.Text.Encoding.ASCII.GetString(bufferLectura)
  49.                .nombre = .nombre.Substring(0, .nombre.IndexOf("$"))
  50.                'Luego el thread.
  51.                .thre = New Thread(AddressOf leerCliente) 'Este thread escucha los mensajes del cliente.
  52.                'Asignamos al cliente que acaba de entrar a la variable global cli.
  53.                cli = infoClienteActual
  54.                'Guardamos en el hashtable los datos del cliente. Usamos synclock para que se ejecute solo eso.
  55.                SyncLock Me
  56.                    'Compruebo si ya exite el nick.
  57.                    comprobarNick()
  58.                    'Si no existe el nick, lo guardo en el hashtable.
  59.                    If cli.nombre <> Nothing Then
  60.                        clientes.Add(clienteActual, infoClienteActual)
  61.                        'Iniciamos la escucha.
  62.                        .thre.Start()
  63.                        'Lleno el listbox con los clientes.
  64.                        llenarlistbox()
  65.                        'Muestro un mensaje de conexion en el servidor.
  66.                        joined()
  67.                    End If
  68.                End SyncLock
  69.            End While
  70.        End With
  71.    End Sub
  72.  
  73.    Private Sub leerCliente()
  74.        Dim IDReal As Net.IPEndPoint 'ID del cliente que envia algo para leer.
  75.        Dim bufferLectura() As Byte 'Aqui se guardara el mensaje que llega.
  76.        Dim infoClienteActual As infoCliente 'Aqui se guardara la informacion del cliente.
  77.        Dim ret As Integer 'Aqui se guarda la longitud del mensaje.
  78.        IDReal = clienteActual 'Guardamos el cliente actual.
  79.        infoClienteActual = clientes(IDReal) 'Obtenemos los datos de la coleccion que corresponden a ese cliente.
  80.        'Con el cliente seleccionado de la coleccion, obtenemos el mensaje.
  81.        With infoClienteActual
  82.            While True
  83.                'Si el socket esta conectado, leo el mensaje.
  84.                If .sock.Connected Then
  85.                    bufferLectura = New Byte(100) {}
  86.                    Try
  87.                        'Me quedo esperando a que llegue un mensaje desde el cliente
  88.                        ret = .sock.Receive(bufferLectura, bufferLectura.Length, SocketFlags.None)
  89.                        If ret > 0 Then
  90.                            'Guardo el mensaje recibido
  91.                            .ultimosDatos = Encoding.ASCII.GetString(bufferLectura)
  92.                            clientes(IDReal) = infoClienteActual
  93.                            'Guardo el cliente actual para usar el nick y el mensaje.
  94.                            cli = infoClienteActual
  95.                            'Se recibe el mensaje y se muestra en el RichTextBox.
  96.                            escribirMensaje()
  97.                            'Reenvio el mensaje a los usuarios para que reciban lo que dicen los demas usuarios.
  98.                            reenviarMensaje()
  99.                        Else
  100.                            'Genero el evento de la finalizacion de la conexion
  101.                            'RaiseEvent ConexionTerminada(IDReal)
  102.                            Exit While
  103.                        End If
  104.                    Catch ex As Exception
  105.                        If Not .sock.Connected Then
  106.                            'Genero el evento de la finalizacion de la conexion
  107.                            cerrarThread(infoClienteActual.sock)
  108.                            Exit While
  109.                        End If
  110.                    End Try
  111.                End If
  112.            End While
  113.        End With
  114.    End Sub
  115.  
  116.    Private Sub llenarlistbox()
  117.        Dim cliente As infoCliente
  118.        'Si el metodo no puede controlar el listbox, se hace el invoke y luego va al else.
  119.        If Me.InvokeRequired Then
  120.            Me.Invoke(New MethodInvoker(AddressOf llenarlistbox))
  121.        Else
  122.            lstUsuarios.Items.Clear()
  123.            lstUsuarios.Items.Add("USUARIOS")
  124.            For Each cliente In clientes.Values
  125.                lstUsuarios.Items.Add(cliente.nombre)
  126.            Next
  127.        End If
  128.  
  129.    End Sub
  130.  
  131.    Private Sub escribirMensaje()
  132.        'Si el metodo no puede controlar el richtextbox, se hace el invoke y luego va al else.
  133.        If Me.InvokeRequired Then
  134.            Me.Invoke(New MethodInvoker(AddressOf escribirMensaje))
  135.        Else
  136.            rtbConversacion.Text = rtbConversacion.Text & Chr(13) & cli.nombre & " dice: " & cli.ultimosDatos
  137.        End If
  138.    End Sub
  139.  
  140.    Private Sub joined()
  141.        'Si el metodo no puede controlar el richtextbox, se hace el invoke y luego va al else.
  142.        If Me.InvokeRequired Then
  143.            Me.Invoke(New MethodInvoker(AddressOf joined))
  144.        Else
  145.            rtbConversacion.Text = rtbConversacion.Text & cli.nombre & " se ha unido a la sala." & Chr(13)
  146.        End If
  147.    End Sub
  148.  
  149.    Private Sub reenviarMensaje()
  150.        'Creamos un cliente para recorrer la coleccion.
  151.        Dim cliente As infoCliente
  152.        Dim men As String
  153.        If Me.InvokeRequired Then
  154.            Me.Invoke(New MethodInvoker(AddressOf reenviarMensaje))
  155.        Else
  156.            'Men sera el mensaje a enviar.
  157.            men = cli.nombre & Chr(93) & cli.ultimosDatos.Trim() & Chr(91)
  158.            For Each cliente In clientes.Values
  159.                If cliente.nombre <> cli.nombre AndAlso cliente.sock.RemoteEndPoint.ToString <> cli.sock.RemoteEndPoint.ToString Then
  160.                    cliente.sock.Send(Encoding.ASCII.GetBytes(men))
  161.                End If
  162.            Next
  163.        End If
  164.    End Sub
  165.  
  166.    Private Sub comprobarNick()
  167.        'Creo un cliente para recorrer la coleccion.
  168.        Dim cliente As infoCliente
  169.        Dim men As String
  170.        'If Me.InvokeRequired Then
  171.        '    Me.Invoke(New MethodInvoker(AddressOf comprobarNick))
  172.        'Else
  173.        'Men es el mensaje a enviar.
  174.        men = Chr(46) & Chr(1)
  175.        For Each cliente In clientes.Values
  176.            If cliente.nombre = cli.nombre Then
  177.                cli.sock.Send(Encoding.ASCII.GetBytes(men))
  178.                'Si se ha encontrado el nombre del cliente en la coleccion, mando un mensaje determinado y pongo cli a nothing
  179.                'para no guardar nada en el hashtable.
  180.                cli.nombre = Nothing
  181.                Exit Sub
  182.            End If
  183.        Next
  184.        'End If
  185.    End Sub
  186.  
  187.    Private Sub cerrarThread()
  188.        Dim cliente As infoCliente
  189.        'Cierro el thread que se encargaba de escuchar a cada cliente.
  190.        Try
  191.            For Each cliente In clientes.Values
  192.                cliente.thre.Abort()
  193.            Next
  194.        Catch ex As Exception
  195.            Exit Sub
  196.        End Try
  197.    End Sub
  198.  
  199.    Private Sub cerrarThread(ByVal socket As Socket)
  200.        'Cierro el thread que le corresponde al cliente que abandona la sala.
  201.        Dim cliente As infoCliente
  202.        Try
  203.            For Each cliente In clientes
  204.                If cliente.sock.ToString = socket.ToString Then
  205.                    cliente.thre.Abort()
  206.                    'Lo borro de la coleccion.
  207.                    clientes.Remove(socket.RemoteEndPoint)
  208.                End If
  209.            Next
  210.        Catch ex As Exception
  211.            Exit Sub
  212.        End Try
  213.    End Sub
  214. #End Region
  215.  
  216. #Region "BOTONES"
  217.  
  218.    Private Sub Servidor_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
  219.        cerrarThread()
  220.        'Declare an array of processes
  221.        Dim myProcesses() As Process
  222.        'single process variable
  223.        Dim myProcess As Process
  224.        'Get the list of processes
  225.        myProcesses = Process.GetProcesses()
  226.        'Iterate through the process array
  227.        For Each myProcess In myProcesses
  228.            If myProcess.ProcessName = "TCPServer" Then
  229.                myProcess.Kill()
  230.            End If
  231.        Next
  232.    End Sub
  233.  
  234.    Private Sub Servidor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  235.        'En el load, asignamos el puerto de escucha.
  236.        tcpLis = New TcpListener(6666)
  237.        'Iniciamos la escucha.
  238.        tcpLis.Start()
  239.        'Creo un thread para que se quede escuchando la llegada de un cliente.
  240.        thread = New Thread(AddressOf esperarCliente)
  241.        thread.Start()
  242.        rtbConversacion.Text = rtbConversacion.Text & "CHAT" & Chr(13)
  243.    End Sub
  244.  
  245.    Private Sub btnEnviar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnviar.Click
  246.        Dim cliente As infoCliente
  247.        'Mando el mensaje a cada cliente de la coleccion.
  248.        For Each cliente In clientes.Values
  249.            cliente.sock.Send(Encoding.ASCII.GetBytes(txtTexto.Text))
  250.        Next
  251.        txtTexto.Text = ""
  252.    End Sub
  253. #End Region
  254.  
  255. End Class



En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Codigo fuente de CHAT en Visual Basic 6, parte 2
Programación Visual Basic
d(-_-)b 0 3,483 Último mensaje 2 Octubre 2007, 11:24 am
por d(-_-)b
Chat en Java [Sockets]
Java
Debci 2 12,421 Último mensaje 27 Agosto 2009, 19:26 pm
por egyware
[PYTHON]Bajar Codigo Fuente de una Web(Con SOCKETS)
Scripting
mr.blood 0 4,716 Último mensaje 11 Enero 2011, 19:17 pm
por mr.blood
[C]Bajar Codigo Fuente de una Web(SOCKETS Windows)
Programación C/C++
mr.blood 0 3,747 Último mensaje 11 Enero 2011, 19:18 pm
por mr.blood
Problemas con el scroll de mi chat en jquery y sockets
Desarrollo Web
Ali Baba 0 1,499 Último mensaje 27 Julio 2018, 03:48 am
por Ali Baba
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines