0

我正在使用 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("loaded") 也不会执行。

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

有人知道这个突然退出的原因吗?先感谢您。

4

0 回答 0