--
Imports System.Diagnostics
Imports System.Net.Sockets
Imports System.Threading
Public Class Form4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ip = "192.168.1.10" 'SQL Server主機的IP位址。
Dim port = 1433 'SQL Server的port預設是1433。
Dim sw As Stopwatch = New Stopwatch()
sw.Start()
Dim isConnection = TestConn(ip, port)
sw.[Stop]()
Dim message = String.Empty
If isConnection Then
message = "連線成功。 經過{0}秒。"
Else
message = "連線失敗了! 經過{0}秒!"
End If
Dim t = sw.ElapsedMilliseconds / 1000.0
MessageBox.Show(String.Format(message, t))
End Sub
Public Function TestConn(ip As String, port As Integer) As Boolean
Try
Using tc As TcpClient = New TcpClient()
Dim result As IAsyncResult = tc.BeginConnect(ip, port, Nothing, Nothing)
Dim start = Date.Now
Do
SpinWait.SpinUntil(Function() False, 100)
If result.IsCompleted Then Exit Do
Loop While Date.Now.Subtract(start).TotalSeconds < 0.3
If result.IsCompleted Then
tc.EndConnect(result)
Return True
End If
tc.Close()
If Not result.IsCompleted Then
Return False
End If
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
Throw
End Try
Return False
End Function
End Class
沒有留言:
張貼留言