4,356
社区成员
发帖
与我相关
我的任务
分享
Private connectDone As New ManualResetEvent(False)
Private sendDone As New ManualResetEvent(False)
Private receiveDone As New ManualResetEvent(False)
Private response As String = String.Empty
Private iTimeOutM As Integer
Private isConn As Boolean = True 'False
Public Function SendTo(ByVal strHostIP As String, _
ByVal iPort As Integer, _
ByVal iTimeout As Integer, _
ByVal strSend As String, _
ByRef strRecv As String, _
ByVal Merch_ID As String, _
ByVal ULNm As String) As ExSocketState
On Error GoTo go_Err
Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(strHostIP)
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
Dim remoteEP As New IPEndPoint(ipAddress, iPort)
Dim client As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
strRecv = ""
If iTimeout > 0 And iTimeout < 200000 Then
iTimeOutM = iTimeout
Else
iTimeOutM = 500000 '5000
End If
Dim s1 = Now()
SendTo = ExSocketState.ExSocketUnKnown
client.BeginConnect(remoteEP, New AsyncCallback(AddressOf ConnectCallback), client)
Dim s2 = Now()
If connectDone.WaitOne(iTimeOutM, False) = True Then
If isConn = True Then
Send(client, strSend, Merch_ID, ULNm)
If sendDone.WaitOne(iTimeOutM, False) = True Then
If isConn = True Then
Dim state As New StateObject
state.workSocket = client
If Receive(state, Merch_ID, ULNm) Then
strRecv = state.sb.ToString()
If strRecv.Length > 10 Then
strRecv = strRecv.Substring(10, strRecv.Length - 10)
Else
strRecv = ""
End If
SendTo = ExSocketState.ExSocketSucceed
Else
SendTo = ExSocketState.ExSocketUnKnown
End If
Else
SendTo = ExSocketState.ExSocketUnKnown
End If
Else
SendTo = ExSocketState.ExSocketUnKnown
End If
Else
SendTo = ExSocketState.ExSocketNoConnect
End If
Else
SendTo = ExSocketState.ExSocketNoConnect
End If
go_Exit:
If client.Connected = True Then
client.Shutdown(SocketShutdown.Both)
End If
client.Close()
Exit Function
go_Err:
GoTo go_Exit
End Function
Private Sub ConnectCallback(ByVal ar As IAsyncResult)
On Error GoTo go_Err
Dim client As Socket = TryCast(ar.AsyncState, Socket)
If client IsNot Nothing Then
isConn = client.Connected
client.EndConnect(ar)
Else
isConn = False
End If
connectDone.Set()
go_Exit:
Exit Sub
go_Err:
isConn = False
connectDone.Set()
GoTo go_Exit
End Sub