如何在Socket编程VB.net中处理异常

时间:2013-08-03 16:11:01

标签: vb.net sockets exception client

我正在使用VB.net编写客户端/服务器应用程序。 我使用MSDN中的代码连接到服务器:

' ManualResetEvent instances signal completion.
Private Shared connectDone As New ManualResetEvent(False)
Private Shared sendDone As New ManualResetEvent(False)
Private Shared receiveDone As New ManualResetEvent(False)

' The response from the remote device.
Private Shared response As String = String.Empty


Public Shared Sub Main()
    ' Establish the remote endpoint for the socket.
    ' For this example use local machine.
    Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
    Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
    Dim remoteEP As New IPEndPoint(ipAddress, port)

    ' Create a TCP/IP socket.
    Dim client As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

    ' Connect to the remote endpoint.
    client.BeginConnect(remoteEP, New AsyncCallback(AddressOf ConnectCallback), client)

    ' Wait for connect.
    connectDone.WaitOne()

    ' Send test data to the remote device.
    Send(client, "This is a test<EOF>")
    sendDone.WaitOne()

    ' Receive the response from the remote device.
    Receive(client)
    receiveDone.WaitOne()

    ' Write the response to the console.
    Console.WriteLine("Response received : {0}", response)

    ' Release the socket.
    client.Shutdown(SocketShutdown.Both)
    client.Close()
End Sub 'Main

代码工作正常但它不处理异常主要是超时异常。 我改变如下:

Private ConnectionDone As New ManualResetEvent(False)    

Public Function SendNetworkRequest(ByVal IPAddress As IPAddress, ByVal Port As Integer) As Boolean
    Dim RemoteEndPoint As New IPEndPoint(IPAddress, Port)

    'TCP/IP Socket
    Dim Client As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)        

    'Start connection
    Try
        Client.BeginConnect(RemoteEndPoint, New AsyncCallback(AddressOf ConnectCallBack), Client)
        ConnectionDone.WaitOne()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

    Return True
End Function

Private Sub ConnectCallBack(ByVal Ar As IAsyncResult)
    Dim Socket As Socket = CType(Ar.AsyncState, Socket)
    Socket.EndConnect(Ar)
    MsgBox("connected to " & Socket.RemoteEndPoint.ToString())
    ConnectionDone.Set()
End Sub

但是当使用错误的IP地址和端口执行以引发异常时,应用程序就会停止而不执行任何操作。知道从Form_Load事件调用此函数,甚至不执行以下MsgBox(“已加载”)。

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    SendNetworkRequest(GV_ServerAddress, GV_ServerPort)
    MsgBox("Loaded")
End Sub

有没有知道这个突然退出的原因? 提前谢谢你。

0 个答案:

没有答案