現在非同期通信のソフト(listener)を作成中です。 以下のソースのように作成しているのですが、途中で通信ポートを 切断すると、エラーが発生してしまいます。受信を行ったあと、切断すれば エラーは発生しません。 いろいろ調べたのですが、分かりませんでした。解決方法をご存知の方がみえましたらご教授願います。 -------------------------------------------------------------- Private Class StateObject Public workSocket As Socket = Nothing Public Const BufferSize As Integer = 1024 Public Buffer(BufferSize) As Byte Public sb As New StringBuilder End Class
Private ipHostInfo As IPHostEntry Private ipAddress As IPAddress Private remoteEP As IPEndPoint
listener = New Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp)
Try listener.Bind(remoteEP)
Dim state As New StateObject
state.workSocket = listener listener.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, _ New AsyncCallback(AddressOf ReadCallBack), state) Catch ex As Exception
End Try
End Sub
Private Sub ReadCallBack(ByVal ar As IAsyncResult)
Try Dim state As StateObject = CType(ar.AsyncState, StateObject) Dim handler As Socket = state.workSocket
Dim bytesRead As Integer = handler.EndReceive(ar)
If bytesRead > 0 Then ' There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.Buffer, 0, _ bytesRead))
'// 受信処理 //
End If Catch ex As Exception '// 途中で通信を強制切断するとエラーが発生!! // End Try
分類:[.NET]
現在非同期通信のソフト(listener)を作成中です。
以下のソースのように作成しているのですが、途中で通信ポートを
切断すると、エラーが発生してしまいます。受信を行ったあと、切断すれば
エラーは発生しません。
いろいろ調べたのですが、分かりませんでした。解決方法をご存知の方がみえましたらご教授願います。
--------------------------------------------------------------
Private Class StateObject
Public workSocket As Socket = Nothing
Public Const BufferSize As Integer = 1024
Public Buffer(BufferSize) As Byte
Public sb As New StringBuilder
End Class
Private ipHostInfo As IPHostEntry
Private ipAddress As IPAddress
Private remoteEP As IPEndPoint
private listener As Socket
Public Sub subRecv()
ipHostInfo = Dns.Resolve(Dns.GetHostName)
ipAddress = ipHostInfo.AddressList(0)
remoteEP = New IPEndPoint(ipAddress, mintPortNum)
listener = New Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp)
Try
listener.Bind(remoteEP)
Dim state As New StateObject
state.workSocket = listener
listener.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, _
New AsyncCallback(AddressOf ReadCallBack), state)
Catch ex As Exception
End Try
End Sub
Private Sub ReadCallBack(ByVal ar As IAsyncResult)
Try
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim handler As Socket = state.workSocket
Dim bytesRead As Integer = handler.EndReceive(ar)
If bytesRead > 0 Then
' There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.Buffer, 0, _
bytesRead))
'// 受信処理 //
End If
Catch ex As Exception
'// 途中で通信を強制切断するとエラーが発生!! //
End Try
End Sub