Código
Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub Dim clientSocket As Socket Dim byteData(1023) As Byte Private Sub OnConnect(ByVal ar As IAsyncResult) clientSocket.EndConnect(ar) clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), clientSocket) End Sub Private Sub OnDisconnect(ByVal ar As IAsyncResult) Dim client As Socket = ar.AsyncState client.EndDisconnect(ar) clientSocket.Close() clientSocket = Nothing End Sub Private Sub OnRecieve(ByVal ar As IAsyncResult) Dim client As Socket = ar.AsyncState client.EndReceive(ar) Dim bytesRec As Byte() = byteData Dim message As String = System.Text.Encoding.ASCII.GetString(bytesRec) Read(message) clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), clientSocket) End Sub Delegate Sub _Read(ByVal msg As String) Private Sub Read(ByVal msg As String) If InvokeRequired Then Invoke(New _Read(AddressOf Read), msg) Exit Sub End If RichTextBox1.Text &= msg End Sub Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) Dim ipAddress As IPAddress = IPAddress.Parse("127.0.0.1") Dim ipEndPoint As IPEndPoint = New IPEndPoint(ipAddress, 8800) clientSocket.BeginConnect(ipEndPoint, New AsyncCallback(AddressOf OnConnect), Nothing) End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click clientSocket.BeginDisconnect(False, New AsyncCallback(AddressOf OnDisconnect), clientSocket) End Sub End Class
Cada vez que doy en el Boton desconectar me salta una exepcion en OnReceive de que el objeto esta Dispose, alguien me puede explicar porque es que se dispara ese evento.
Lo otro es que en el lado del servidor no se entera de que el socket fue cerrado, para que el se percatara de esto tendria que hacer una especie de thread cada cierto tiempo verificando si el socket esta vivo ??
Como explican aqui
http://stackoverflow.com/questions/722240/instantly-detect-client-disconnection-from-server-socket
Salu2
Lo que busco es detectar cuando un cliente se conecta y desconecta tanto para el cliente como el servidor.