Async socket

Contenu du snippet

ASync Socket est une simple class de gestion des sockets asynchrone, juste un problème au niveau des évenements.

Source / Exemple :


#Region "Imports"
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
#End Region

Public Class ASyncSocket

#Region "Déclarations"

    Private Socket As Socket
    Private Buffer(1024) As Byte
    Private States As New List(Of SocketStates)

#End Region

#Region "Enumération"

    Enum SocketStates
        IsConnecting = 0
        IsAccepting = 1
        IsSending = 2
        IsReceving = 3
        IsDisconnecting = 4
    End Enum

#End Region

#Region "Evènements"

    Public Event OnListen()
    Public Event OnListenFailed(ByVal Exception As Exception)

    Public Event OnConnect()
    Public Event OnConnectFailed(ByVal Exception As Exception)

    Public Event OnSend()
    Public Event OnSendFailed(ByVal Exception As Exception)

    Public Event OnAccept(ByVal AcceptedSocket As ASyncSocket)
    Public Event OnAcceptFailed(ByVal Exception As Exception)

    Public Event OnReceive(ByVal Stream As String)
    Public Event OnReceiveFailed(ByVal Exception As Exception)

    Public Event OnDisconnect()
    Public Event OnDisconnectFailed(ByVal Exception As Exception)

#End Region

#Region "Conctructeurs"

    Public Sub New()
        Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    End Sub

    Public Sub New(ByVal Socket As Socket, Optional ByVal ListenData As Boolean = False)
        Me.Socket = Socket
        If ListenData Then Me.ListenData()
    End Sub

    Public Sub New(ByVal Ip As String, ByVal Port As Integer)
        Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Connect(Ip, Port)
    End Sub

    Public Sub New(ByVal Port As Integer)
        Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Listen(Port)
    End Sub

#End Region

#Region "Fonctions"

    Public Sub Connect(ByVal Ip As String, ByVal Port As Integer)

        If (Socket Is Nothing) Then Exit Sub

        Try

            States.Add(SocketStates.IsConnecting)
            Socket.BeginConnect(New IPEndPoint(Net.IPAddress.Parse(Ip), Port), AddressOf ConnectCallBack, Socket)

        Catch Exception As Exception
            States.Remove(SocketStates.IsConnecting)
            RaiseEvent OnConnectFailed(Exception)
        End Try

    End Sub

    Public Sub Send(ByVal Stream As String)

        If (Not IsConnected) OrElse (Socket Is Nothing) Then Exit Sub

        Try

            Dim Buffer() As Byte = Encoding.Default.GetBytes(Stream)

            Me.States.Add(SocketStates.IsSending)
            Me.Socket.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, AddressOf OnSendCallBack, Nothing)

        Catch Exception As Exception
            Me.States.Remove(SocketStates.IsSending)
            RaiseEvent OnSendFailed(Exception)
        End Try

    End Sub

    Public Sub Disconnect()

        If (Not IsConnected) OrElse (Socket Is Nothing) Then Exit Sub

        Try

            While Not States.Count = 0
                Thread.Sleep(1)
            End While

            States.Add(SocketStates.IsDisconnecting)
            Socket.BeginDisconnect(False, AddressOf OnDisconnectCallBack, Nothing)

        Catch Exception As Exception
            States.Remove(SocketStates.IsDisconnecting)
            RaiseEvent OnDisconnectFailed(Exception)
        End Try

    End Sub

    Public Sub Listen(ByVal Port As Integer)

        If (Socket Is Nothing) Then Exit Sub

        Try

            Socket.Bind(New IPEndPoint(IPAddress.Parse("0.0.0.0"), Port))
            Socket.Listen(0)
            ListenSocket()

            RaiseEvent OnListen()

        Catch Exception As Exception
            RaiseEvent OnListenFailed(Exception)
        End Try

    End Sub

    Public Sub ListenEvent()
        RaiseEvent OnListen()
    End Sub

    Private Sub ListenSocket()

        If (Socket Is Nothing) Then Exit Sub

        Try

            States.Add(SocketStates.IsAccepting)
            Socket.BeginAccept(AddressOf OnAcceptCallBack, Nothing)

        Catch Exception As Exception
            States.Remove(SocketStates.IsAccepting)
            RaiseEvent OnAcceptFailed(Exception)
        End Try

    End Sub

    Private Sub ListenData()

        If (Not IsConnected) OrElse (Socket Is Nothing) Then Exit Sub

        Try

            States.Add(SocketStates.IsReceving)
            Socket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, AddressOf OnReceiveCallBack, Nothing)

        Catch Exception As Exception
            States.Remove(SocketStates.IsReceving)
            RaiseEvent OnReceiveFailed(Exception)
        End Try

    End Sub

    Private Function StateIs(ByVal SocketState As SocketStates) As Boolean
        If States.Contains(SocketState) Then Return True
        Return False
    End Function

#End Region

#Region "Callbacks"

    Private Sub ConnectCallBack(ByVal IAsyncResult As IAsyncResult)

        If (Socket Is Nothing) OrElse (IAsyncResult Is Nothing) OrElse (Not StateIs(SocketStates.IsConnecting)) Then Exit Sub

        Try

            Socket.EndConnect(IAsyncResult)
            States.Remove(SocketStates.IsConnecting)
            ListenData()

            RaiseEvent OnConnect()

        Catch Exception As Exception
            Me.States.Remove(SocketStates.IsConnecting)
            RaiseEvent OnConnectFailed(Exception)
        End Try

    End Sub

    Private Sub OnReceiveCallBack(ByVal IAsyncResult As IAsyncResult)

        If (Not IsConnected) OrElse (Socket Is Nothing) OrElse (IAsyncResult Is Nothing) OrElse (Not StateIs(SocketStates.IsReceving)) Then Exit Sub

        Try

            Dim Bytes As Integer = Socket.EndReceive(IAsyncResult)
            States.Remove(SocketStates.IsReceving)

            If Bytes > 0 Then

                Dim Stream As String = Encoding.Default.GetString(Buffer)
                Array.Clear(Buffer, 0, Buffer.Length - 1)

                RaiseEvent OnReceive(Stream)

            Else

                Dim Socket As Socket = CType(IAsyncResult.AsyncState, Socket)
                Dim AsyncSocket As New ASyncSocket(Socket)

                AsyncSocket.Disconnect()

            End If

            ListenData()

        Catch Exception As Exception
            States.Remove(SocketStates.IsReceving)
            RaiseEvent OnReceiveFailed(Exception)
        End Try

    End Sub

    Private Sub OnSendCallBack(ByVal IAsyncResult As IAsyncResult)

        If (Not IsConnected) OrElse (Socket Is Nothing) OrElse (IAsyncResult Is Nothing) OrElse (Not StateIs(SocketStates.IsSending)) Then Exit Sub

        Try

            Socket.EndSend(IAsyncResult)
            States.Remove(SocketStates.IsSending)

            RaiseEvent OnSend()

        Catch Exception As Exception
            States.Remove(SocketStates.IsSending)
            RaiseEvent OnSendFailed(Exception)
        End Try

    End Sub

    Private Sub OnDisconnectCallBack(ByVal IAsyncResult As IAsyncResult)

        If (Socket Is Nothing) OrElse (IAsyncResult Is Nothing) OrElse (Not StateIs(SocketStates.IsDisconnecting)) Then Exit Sub

        Try

            Socket.EndDisconnect(IAsyncResult)
            States.Remove(SocketStates.IsDisconnecting)

            RaiseEvent OnDisconnect()

        Catch Exception As Exception
            States.Remove(SocketStates.IsDisconnecting)
            RaiseEvent OnDisconnectFailed(Exception)
        End Try

    End Sub

    Private Sub OnAcceptCallBack(ByVal IAsyncResult As IAsyncResult)

        If (Socket Is Nothing) OrElse (IAsyncResult Is Nothing) OrElse (Not StateIs(SocketStates.IsAccepting)) Then Exit Sub

        Try

            Dim AcceptedSocket As New ASyncSocket(Socket.EndAccept(IAsyncResult), True)
            States.Remove(SocketStates.IsAccepting)
            ListenSocket()

            RaiseEvent OnAccept(AcceptedSocket)

        Catch Exception As Exception
            States.Remove(SocketStates.IsAccepting)
            RaiseEvent OnAcceptFailed(Exception)
        End Try

    End Sub

#End Region

#Region "Propriétés"

    Public ReadOnly Property IsConnected
        Get

            If (Socket Is Nothing) Then Return False

            Try
                Return Socket.Connected
            Catch Exception As Exception
                Return False
            End Try

        End Get
    End Property

    Public ReadOnly Property NetworEndPoint() As IPEndPoint
        Get

            If (Socket Is Nothing) Then Return Nothing

            Try
                Return CType(Socket.RemoteEndPoint, IPEndPoint)
            Catch Exception As Exception
                Return Nothing
            End Try

        End Get
    End Property

    Public ReadOnly Property NetworkAddress() As IPAddress
        Get

            If (Socket Is Nothing) Then Return Nothing

            Try
                Return CType(Socket.RemoteEndPoint, IPEndPoint).Address
            Catch Exception As Exception
                Return Nothing
            End Try

        End Get
    End Property

    Public ReadOnly Property NetworkPort() As Integer
        Get

            If (Socket Is Nothing) Then Return Nothing

            Try
                Return CType(Socket.RemoteEndPoint, IPEndPoint).Port
            Catch Exception As Exception
                Return Nothing
            End Try

        End Get
    End Property

#End Region

End Class

Conclusion :


Voir source ;)

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.