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

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP)
| | | |-+  Programación Visual Basic (Moderadores: LeandroA, seba123neo)
| | | | |-+  Winsock
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Winsock  (Leído 2,205 veces)
vivachapas


Desconectado Desconectado

Mensajes: 612



Ver Perfil
Winsock
« en: 24 Marzo 2007, 00:05 am »

investigando sobre el control Winsock vi q casi todos los ej los hacian con un "chat" a si q empese haciendo eso... y lo fui mejorando... y esto es lo q me quedo

en un form:
un winsock
dos textbox
dos timer
un commandbutton


Citar
Dim texto As String
Dim ip As String
Dim port As Long

Private Sub Form_Load()
ip = "127.0.1"
port = 142
Timer2.Interval = 1
Timer2.Enabled = False
Timer1.Interval = 1750
End Sub

Private Sub Command3_Click()
Dim enviar As String
On Error Resume Next
If Winsock1.State = 7 Then
enviar = Text2.Text
Winsock1.SendData enviar
texto = Text1.Text + "#" + enviar
Text1.Text = texto
Text2.Text = ""
Else
MsgBox "No estas conectado", vbCritical, "Error"
End If
End Sub

Private Sub Text1_Change()
Text1.Text = texto
End Sub

Private Sub Text2_Change()
If Text2.Text = "" Then
Command3.Enabled = False
Else
Command3.Enabled = True
End If
End Sub

Private Sub Timer1_Timer()
On Error Resume Next
If Winsock1.State <> 7 Then
Winsock1.Close
Winsock1.Connect ip, port
Timer2.Enabled = True
End If
End Sub

Private Sub Timer2_Timer()
On Error Resume Next
If Winsock1.State = 7 Then
Winsock1.SendData "Se conecto"
Timer2.Enabled = False
End If
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Beep
Dim datos As String
Winsock1.GetData datos
texto = Text1.Text + "//" + datos
Text1.Text = texto
End Sub


en otro form:
un winsock
dos textbox
un commandbutton


Citar
Dim texto As String

Private Sub Command3_Click()
Dim enviar As String
On Error Resume Next
If Winsock1.State = 7 Then
enviar = Text2.Text
Winsock1.SendData enviar
texto = Text1.Text + "#" + enviar
Text1.Text = texto
Text2.Text = ""
Else
MsgBox "No estas conectado", vbCritical, "Error"
Winsock1.Close
Winsock1.Listen
End If
End Sub

Private Sub Form_Load()
Winsock1.Listen
End Sub

Private Sub Text1_Change()
Text1.Text = texto
End Sub

Private Sub Text2_Change()
If Text2.Text = "" Then
Command3.Enabled = False
Else
Command3.Enabled = True
End If
End Sub

Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
Winsock1.Close
Winsock1.Accept requestID
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim datos As String
Winsock1.GetData datos
Beep
texto = Text1.Text + "//" + datos
Text1.Text = texto
End Sub


bueno... espero q a algun novato le sirva para aprender algo... y q les alla gustado...



lo q les queria preguntar... como hacer para q cuando se envie el texto se ponga en otra linea... xq si no queda todo en una sola y es muy feo... (por eso puse los separadores # y //)


En línea

~~
Ex-Staff
*
Desconectado Desconectado

Mensajes: 2.981


Ver Perfil WWW
Re: Winsock
« Respuesta #1 en: 24 Marzo 2007, 00:13 am »

Pues poniendo la propieda multiline en true y usando vbCrLf o "||" q es lo mismo ;)


En línea

vivachapas


Desconectado Desconectado

Mensajes: 612



Ver Perfil
Re: Winsock
« Respuesta #2 en: 24 Marzo 2007, 00:37 am »

mira lo q hago.. para ver q hago mal xq no me funciona

Citar
Private Sub Command3_Click()
Dim enviar As String
On Error Resume Next
If Winsock1.State = 7 Then
enviar = Text2.Text
Winsock1.SendData enviar
texto = Text1.Text + "#" + enviar + "||"
Text1.Text = texto
Text2.Text = ""
Else
MsgBox "No estas conectado", vbCritical, "Error"
End If
End Sub


lo modifico en esa parte... pero nada... tb probe en otras partes... pero nada... si me decis donde iria te lo agradezco ;)
« Última modificación: 24 Marzo 2007, 00:44 am por vivachapas » En línea

vivachapas


Desconectado Desconectado

Mensajes: 612



Ver Perfil
Re: Winsock
« Respuesta #3 en: 24 Marzo 2007, 00:50 am »

ya pude!!!! jaja con la funcion vbCrLf

muchas gracias;)

ahora lo q me gustaria tb hacer es q cuando se presione enter el texto se envie solo...

« Última modificación: 24 Marzo 2007, 00:56 am por vivachapas » En línea

Syphroot

Desconectado Desconectado

Mensajes: 268


All You Need To Do Is Follow The Worms


Ver Perfil WWW
Re: Winsock
« Respuesta #4 en: 25 Marzo 2007, 10:54 am »

en el evento KeyPress del textbox haz un condicional:

Código:
if KeyAscii = 13 then
    Enviar()
End if

o en el evento KeyDown igual:

Código:
if KeyCode = 13 then
    Enviar()
End if
En línea

Lao

Desconectado Desconectado

Mensajes: 27



Ver Perfil WWW
Re: Winsock
« Respuesta #5 en: 28 Marzo 2007, 06:29 am »

Bien ahi, cuando quise aprender eso tarde mucho jeje , ahora estoy peleando para poder ver una imagen como el msn los avatares xD jaja si sabes algo avisame adios.
En línea

vivachapas


Desconectado Desconectado

Mensajes: 612



Ver Perfil
Re: Winsock
« Respuesta #6 en: 29 Marzo 2007, 03:07 am »

para q uno ponga un avatar... el avatar se tiene q enviar por el winsock al otro usuario... para hacer eso es mas complicado... debes usar codigos q fraccionen el archivo en paquetes y enviarlos uno por uno y luego cuando el otro los reciba q los junte... es mas complicado y la verdad todavia no llegue a entenderlo bien del todo  :huh:
pero seguro alguien nos explica... jeje
En línea

vivachapas


Desconectado Desconectado

Mensajes: 612



Ver Perfil
Re: Winsock
« Respuesta #7 en: 29 Marzo 2007, 04:02 am »

bueno bueno... de nuevo... ya q entre antes me decidi a poner el chat... lo cambie mucho desde el ultimo post ya q encontre una web en la q habia un manual para hacer un chat bastante basico y yo lo modifique

el manual original es de:

http://www.monografias.com/trabajos30/tutorial-visual-basic/tutorial-visual-basic.shtml


bueno pongo aca los form:

Cliente:
textbox1, scroll vertical, funcion multiline
textbox2
commandbutton1, caption "Enviar"
commandbutton4, caption "Conectar"
commandbutton3, captio "Desconectar", enabled = false
timer1
winsock1


Citar
Dim ip As String, puerto As Long, nick As String, c As Byte

Private Sub Command2_Click()
Command2.Enabled = False
Command3.Enabled = True
'asignamos los datos de conexion
'conectamos el socket
Winsock1.Connect ip, puerto
End Sub

Private Sub Form_Load()
nick = InputBox("Ingrese su nick", "Nick")
ip = "127.0.0.1"
puerto = 23
a = 1
c = 0
End Sub

Private Sub Text2_Change()
If Text2.Text = "" Then
Command1.Enabled = False
Else
Command1.Enabled = True
End If
End Sub

Private Sub Text2_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then Command1_Click
End Sub

Private Sub Timer1_Timer()
c = c + 1
Select Case c
Case 1
Form1.Left = Form1.Left + 40
Form1.Top = Form1.Top + 65
Beep
Case 2
Form1.Left = Form1.Left - 52
Form1.Top = Form1.Top + 69
Beep
Case 3
Form1.Left = Form1.Left + 30
Form1.Top = Form1.Top - 32
Beep
Case 4
Form1.Left = Form1.Left + 25
Form1.Top = Form1.Top + 50
Beep
Case 5
Form1.Left = Form1.Left + 40
Form1.Top = Form1.Top + 65
Beep
Case 6
Form1.Left = Form1.Left - 52
Form1.Top = Form1.Top + 69
Beep
Case 7
Form1.Left = Form1.Left + 30
Form1.Top = Form1.Top - 32
Beep
Case 8
Form1.Left = Form1.Left - 90
Form1.Top = Form1.Top - 130
Beep
Timer1.Interval = 0
c = 0
End Select
End Sub

Private Sub Winsock1_Connect()
'desplegamos un mensaje en la ventana
Text1.Text = Text1.Text & _
"*** Conexion establecida." & vbCrLf
'desplazamos el scroll
Text1.SelStart = Len(Text1.Text)
End Sub
Private Sub Winsock1_Close()
'cierra la conexion
Winsock1.Close
'desplegamos un mensaje en la ventana
Text1.SelStart = Len(Text1.Text)
Text1.Text = Text1.Text & "*** Conexion cerrada por Agustín." & vbCrLf
Text1.SelStart = Len(Text1.Text)
End Sub

Private Sub Command3_Click()
Command3.Enabled = False
Command2.Enabled = True
'cierra la conexion
Winsock1.Close
'desplegamos un mensaje en la ventana
Text1.Text = Text1.Text & _
"*** Conexion cerrada por el usuario." & vbCrLf
'desplazamos el scroll
Text1.SelStart = Len(Text1.Text)
End Sub

Private Sub Command1_Click()
If Winsock1.State = 7 Then
'enviamos el contenido de Text2
Winsock1.SendData nick & "> " & Text2.Text
Text2.Text = ""
Else
Text1.Text = Text1.Text & "***Debes establecer una conexión primero." & vbCrLf
End If
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Beep
Dim Buffer As String 'variable para guardar los datos
'obtenemos los datos y los guardamos en una variable
Winsock1.GetData Buffer
If Buffer = "Servidor> zumbido" & vbCrLf Then
Timer1.Interval = 100
End If
'apuntamos al final del contenido del TextBox e
'insertamos los nuevos datos obtenidos
Text1.SelStart = Len(Text1.Text) 'coloca el cursor al final del contenido
Text1.Text = Text1.Text & Buffer 'mostramos los datos
Text1.SelStart = Len(Text1.Text) 'coloca el cursor al final del contenido
End Sub

Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
'cerramos la conexion
Winsock1.Close
If Number = 10061 Then
Text1.Text = Text1.Text & "***No has podido conectarte con el servidor ya que este no esta conectado." & vbCrLf
Command2.Enabled = True
Command3.Enabled = False
Else
'mostramos informacion sobre el error
MsgBox "Error numero " & Number & ": " & Description, vbCritical
End If
End Sub




Servidor:
textbox1, scroll vertical, funcion multiline
textbox2
commandbutton1, caption "Enviar"
commandbutton4, caption "Escuchar"
commandbutton3, captio "Desconectar", enabled = false
timer1
winsock1
winsock2, index 0

Citar
Private Sub Command2_Click()
Command2.Enabled = False
Command3.Enabled = True
'cerramos cualquier conexion previa
Winsock1.Close
'asignamos el puerto local que abriremos
Winsock1.LocalPort = 23
'deja el socket esuchando conexiones
Winsock1.Listen
'desplegamos un mensaje en la ventana
Text1.SelStart = Len(Text1.Text)
Text1.Text = Text1.Text & "*** Esuchando conexiones." & vbCrLf
Text1.SelStart = Len(Text1.Text)
End Sub

Private Sub Command3_Click()
Command3.Enabled = False
Command2.Enabled = True
'cierra la conexion
Winsock1.Close
'desplegamos un mensaje en la ventana
Text1.SelStart = Len(Text1.Text)
Text1.Text = Text1.Text & "*** Conexion cerrada por el usuario." & vbCrLf
Text1.SelStart = Len(Text1.Text)
End Sub

Private Sub Text2_Change()
If Text2.Text = "" Then
Command1.Enabled = False
Else
Command1.Enabled = True
End If
End Sub

Private Sub Text2_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then Command1_Click
End Sub

Private Sub Winsock1_Close()
'cierra la conexion
Winsock1.Close
'desplegamos un mensaje en la ventana
Text1.SelStart = Len(Text1.Text)
Text1.Text = Text1.Text & "*** Conexion cerrada por el Servidor." & vbCrLf
Text1.SelStart = Len(Text1.Text)
End Sub

Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
'cerramos la conexion
Winsock1.Close
'mostramos informacion sobre el error
MsgBox "Error numero " & Number & ": " & Description, vbCritical
End Sub

Private Sub Command1_Click()
Dim numElementos As Integer 'numero de sockets
Dim i As Integer 'contador
'obtiene la cantidad de Winsocks que tenemos
numElementos = Winsock2.UBound
'recorre el arreglo de sockets
For i = 0 To numElementos
'si el socket se encuentra conectado...
If Winsock2(i).State = sckConnected Then
'enviamos el contenido de Text2
Winsock2(i).SendData "Servidor> " & Text2.Text & vbCrLf
'apuntamos al final del contenido del TextBox e
'insertamos los nuevos datos obtenidos
Text1.SelStart = Len(Text1.Text) 'coloca el cursor al final del contenido
Text1.Text = Text1.Text & "Servidor> " & Text2.Text & vbCrLf 'mostramos los datos
Text1.SelStart = Len(Text1.Text) 'coloca el cursor al final del contenido
End If
Next
'borramos Text2
Text2.Text = ""
End Sub

Private Sub Winsock2_DataArrival(Index As Integer, ByVal bytesTotal As Long)
Beep
Dim Buffer As String 'variable para guardar los datos
'obtenemos los datos y los guardamos en una variable
Winsock2(Index).GetData Buffer
'apuntamos al final del contenido del TextBox e
'insertamos los nuevos datos obtenidos
Text1.SelStart = Len(Text1.Text) 'coloca el cursor al final del contenido
Text1.Text = Text1.Text & Buffer & vbCrLf 'mostramos los datos
Text1.SelStart = Len(Text1.Text) 'coloca el cursor al final del contenido
Dim cant As Integer
Dim c As Integer
cant = Winsock2.UBound
For c = 0 To cant
If Winsock2(c).State = sckConnected Then
Winsock2(c).SendData Buffer & vbCrLf
End If
Next
End Sub

Private Sub Winsock2_Close(Index As Integer)
'cierra la conexion
Winsock2(Index).Close
'desplegamos un mensaje en la ventana
Text1.SelStart = Len(Text1.Text)
Text1.Text = Text1.Text & "Sock" & Index & ":*** Conexion cerrada por el Cliente." & vbCrLf
Text1.SelStart = Len(Text1.Text)
End Sub

Private Sub Winsock2_Error(Index As Integer, ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
'cerramos la conexion
Winsock2(Index).Close
'mostramos informacion sobre el error
MsgBox "Error numero " & Number & ": " & Description, vbCritical
End Sub

'Carga un nuevo socket al arreglo y devuelve su indice
Private Function NuevoSocket() As Integer
Dim numElementos As Integer 'numero de sockets
Dim i As Integer 'contador
'obtiene la cantidad de Winsocks que tenemos
numElementos = Winsock2.UBound
'recorre el arreglo de sockets
For i = 0 To numElementos
'si algun socket ya creado esta inactivo
'utiliza este mismo para la nueva conexion
If Winsock2(i).State = sckClosed Then
NuevoSocket = i 'retorna el indice
Exit Function 'abandona la funcion
End If
Next
'si no encuentra sockets inactivos
'crea uno nuevo y devuelve su identidad
Load Winsock2(numElementos + 1) 'carga un nuevo socket al arreglo
'devuelve el nuevo indice
NuevoSocket = Winsock2.UBound
End Function

Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
Beep
Dim numSocket As Integer 'el numero del socket
'mostramos un mensaje en la ventana
Text1.SelStart = Len(Text1.Text)
Text1.Text = Text1.Text & "*** Peticion numero " & requestID & vbCrLf
Text1.SelStart = Len(Text1.Text)
'creamos un nuevo socket
numSocket = NuevoSocket
'aceptamos la conexion con el nuevo socket
Winsock2(numSocket).Accept requestID
'desplegamos un mensaje en la ventana
Text1.SelStart = Len(Text1.Text)
Text1.Text = Text1.Text & "Sock" & numSocket & ":*** Conexion aceptada, listo para interactuar." & vbCrLf
Text1.SelStart = Len(Text1.Text)
End Sub



explico un poco...
*el cliente se conecta con el server
*cuando un cliente envia un dato no se agrega directamente al text1 si no q se manda al server y este lo vuelve a enviar... esto lo hice para q si hay mas de un cliente todos vean todo... y asi poder hablar entre muchos todos juntos
*el servidor si envia la palabra "zumbido" les envia un zumbido a todos los clientes
*bueno... les parecera raro q tenga dos winsock ya q la mayoriria de los programas tienen uno les explico el winsock1 queda siempre a la escucha y cuando capta una nueva conecxion le designa un puerto en el winsock2 y vuelve a quedarse a la escucha
*presionando enter se envia el texto


no se q mas... cualquier duda preguntenme o sugerencia...
tb pueden consultar el link ya q repito q es una modificacion de un manual... el link lo saque de este foro... pero no me acuerdo de donde...


pueden bajar el archivo de aca:
http://rapidshare.com/files/23274763/Mini_Chat.rar


espero no olvidarme nada


SALUDOS::
« Última modificación: 26 Mayo 2007, 17:32 pm por vivachapas » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines