日期:2012-08-28  浏览次数:20477 次

    
    
    ' Nested enum for supported states
    Public Enum Status
        Listening
        Connected
    End Enum 'Status
    
    
    ' Start up the talker's functionality
    Public Sub Start()
        ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf EstablishSocket))
    End Sub 'Start
    
    
    ' Establish a socket connection and start receiving
    Private Sub EstablishSocket(ByVal state As Object)
        Try
            ' If not client, setup listner
            If Not client Then
                Dim listener As Socket

                Try
                    listener = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                    listener.Blocking = True
                    listener.Bind(endPoint)
                    SetStatus(Status.Listening)
                    listener.Listen(0)
                    socket = listener.Accept()
                    listener.Close()
                Catch e As SocketException
                    ' If there is already a listener on this port try client
                    If e.ErrorCode = 10048 Then
                        client = True
                        endPoint = New IPEndPoint(Dns.Resolve("127.0.0.1").AddressList(0), endPoint.Port)
                    Else
                        RaiseEvent Notifications(Notification.ErrorNotify, "Error Initializing Socket:" & ControlChars.CrLf & e.ToString())
                    End If
               &n