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

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Programacion con Sockets
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Programacion con Sockets  (Leído 2,270 veces)
LOUNELSON

Desconectado Desconectado

Mensajes: 2


Ver Perfil
Programacion con Sockets
« en: 19 Noviembre 2012, 01:43 am »

HOLA ME LLAMO LOURDES
PORFAVOR NECESITO AYUDA EN VERDAD PARA APROBAR MI CLASE...DIOS LES BENDIGA
ESTOY PROGRAMANANDO UN SERVER TIPO FTP...LO QUE NECESITO ES ENVIAR UN ARCHIVO DE TEXTO DEL CLIENTE AL SERVER HE AUI ALGUNOS PUNTOS Y EL CODIGO QUE YA TENGO...



CLIENTE...
Una vez seleccionado el archivo, el nombre del mismo debe ser  enviado al servidor por
medio de un mensaje “ARCHIVO: <nombre del archivo>”.
  Después de enviar el nombre del archivo, el cliente debe esperar un mensaje “OK” para
empezar a transmitir el archivo texto. 
  El archivo debe ser transmitido línea por línea.
  Cuando  se  lea  el  fin  de  archivo,  se  debe  enviar  un mensaje  “FIN”  al  servidor  y  debe
desplegar un mensaje “Archivo Transmitido Satisfactoriamente”.


Código:
Imports System.Net 
Imports System.Net.Sockets
Imports System.IO

Public Class Form1
    Dim clienteSocket As New System.Net.Sockets.TcpClient()
    Dim serverStream As NetworkStream
    Dim fs As FileStream = Nothing
    Dim NombreArchivo As String

    Public Sub txtConectar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtConectar.Click
       
        Try
            clienteSocket.Connect(txtIP_FTPServer.Text, txtPuerto_FTPServer.Text)
            txtEstatus.Text = "Estatus : Connectado ..."
            serverStream = clienteSocket.GetStream()
            txtLog.Text = "" & "Conectado" & vbCrLf
        Catch ex As Exception
            txtEstatus.Text = "Error de conexión : " & ex.Message
        End Try
    End Sub
    Private Sub txtBuscarArchivo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBuscarArchivo.Click
        NombreArchivo = "c:\temp\" & txtfileName.Text & ".txt"

        Try                                     
            OpenFileDialog1.ShowDialog()
            NombreArchivo = OpenFileDialog1.FileName
            txtfileName.Text = NombreArchivo

        Catch ex As Exception
            MsgBox("Error al crear/abrir archivo : " & NombreArchivo & " " & ex.Message) 'metodo indica q tipo de error es el que se encuentra
        End Try

    End Sub
    Private Sub btnEnviar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnviar.Click ' enviar informacion
        Dim nombre As String
        nombre = Path.GetFileName(NombreArchivo)

        Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes("ARCHIVO: " & nombre) 'ESTE OBJETO SE NECESITA SIEMPRE
        Dim buffSize As Integer ' PARA QUE EL SERVIDOR SEPA CUANTA INFO SE LE VA A ENVIAR

        Dim inStream(10024) As Byte
        Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream)
        Try
            'PARA ENVIARLE DATA AL SERVIDOR
            serverStream.Write(outStream, 0, outStream.Length) ' PARA ENVIAR LA INFO...ARREGLO DE BYTES, DESDE DOMDE COMIENZA LA INFO, CUANTO LE ESTAMOS ENVIANDO
            serverStream.Flush()
         
            txtLog.Text = txtLog.Text & "Cliente dice >> " & "ARCHIVO: " & nombre

            'Socket recibida del server
            buffSize = clienteSocket.ReceiveBufferSize
            serverStream.Read(inStream, 0, buffSize)
            returndata = System.Text.Encoding.ASCII.GetString(inStream)

            txtLog.Text = txtLog.Text & returndata & vbCrLf

            txtEstatus.Text = "Socket desconectado"

        Catch ex As Exception
            txtEstatus.Text = "Error : " & ex.Message
        End Try
   
    End Sub

    Private Sub btnDesconectar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDesconectar.Click
        serverStream.Dispose() ' CERRAR LA CONEXION
        clienteSocket.Close()
    End Sub
End Class




EL SERVIDOR..........

Después de aceptar la conexión del cliente, el servidor debe parsear el mensaje:
o  Si  el mensaje  inicia  con  el  substring  “NOMBRE:  “, debe  leer  el  resto del  string y
crear el archivo con el nombre  recibido en el mensaje,  luego enviar un mensaje
“OK” al cliente.
o  Si el mensaje  inicia con el substring “FIN”, el servidor debe cerrar el archivo que
creó.
o  Si  el mensaje no  comienza  con ninguna de  las  substrings  anteriores,  el  servidor
debe grabar completamente el mensaje en el archivo de texto.
El servidor debe grabar el archivo en la carpeta c:\temp por default.


Imports System.Net
Imports System.Net.Sockets
Public Class Form1
    Dim serverstream As NetworkStream
    Dim server As TcpListener

    Private Sub btnActivar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnActivar.Click

        Dim IPLocal As IPAddress = IPAddress.Parse(txtIP_FTPServer.Text) 
        Dim Puerto As Integer = Val(txtPuerto_FTPServer.Text)
        Dim clienteSocket As TcpClient
        server = New TcpListener(IPLocal, Puerto)

        Try
            txtLog.Text = "Chat Server activo ...." & vbCrLf
            Application.DoEvents()

            server.Start()
            clienteSocket = server.AcceptTcpClient()

            While (True)
                Dim bytesFrom(10024) As Byte 'ARREGLO DE BYTES
                Dim dataFromClient As String
           
                'Socket recibido del cliente

                Dim networkStream As NetworkStream = clienteSocket.GetStream()
                networkStream.Read(bytesFrom, 0, CInt(clienteSocket.ReceiveBufferSize))

                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) 'CONVERTIR EL ARREGLO DE BYTES Q VIENE A TYPO STRNG , EN CODIF ASSCI, TIPO TEXTO Y SE ASIGNA A DATAFROMCLIENTE
                ' dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$")) 'REMOVER EL SIMBOLO
                Application.DoEvents()

                txtLog.Text = txtLog.Text & "Cliente dice >> " & dataFromClient & vbCrLf

                'Código que responde al cliente

                Dim serverResponse As String = "Servidor dice >> ok"

                Dim sendBytes As [Byte]() = System.Text.Encoding.ASCII.GetBytes(serverResponse)
                networkStream.Write(sendBytes, 0, sendBytes.Length)
                networkStream.Flush()

                txtLog.Text = txtLog.Text & serverResponse & vbCrLf
                Me.Refresh()
            End While
        Catch ex As Exception
            MsgBox("Error " & ex.Message)
        End Try
        server.Stop()

    End Sub
End Class


« Última modificación: 19 Noviembre 2012, 03:58 am por raul338 » En línea

spiritdead

Desconectado Desconectado

Mensajes: 296


Ver Perfil
Re: Programacion con Sockets
« Respuesta #1 en: 19 Noviembre 2012, 04:19 am »

primero que todo, el titulo del post no va en mayus :/

segundo te recomiendo usar serialize de objetos y crees 1 libreria (DLL) con un tipo de structure que usaras al serializar, y asi pdoer transmitirlo del cliente al server

:) la cosa es investigar pero vas bien, al usar sockets


En línea

Facilitador De Tareas - Task Simplifier (FDT)
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
urgente auxilio, programacion en C
Programación C/C++
pipekbzon 2 2,456 Último mensaje 19 Noviembre 2011, 02:31 am
por pipekbzon
programacion en pseudocodigo ayuda urgente
Programación C/C++
kukrin 5 3,389 Último mensaje 21 Abril 2012, 20:19 pm
por s00rk
Ayuda urgente con Programacion c++
Programación C/C++
JuanSeLasprilla 1 2,271 Último mensaje 10 Julio 2013, 01:31 am
por engel lex
AYUDA URGENTE DE PROGRAMACIÓN EN C
Programación C/C++
Adurna 6 2,088 Último mensaje 8 Enero 2014, 15:40 pm
por daryo
AYUDA URGENTE Programacion C#
Programación General
VampireVash 1 1,688 Último mensaje 26 Abril 2014, 01:19 am
por engel lex
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines