|
分類:[VB.NET/VB2005 以降]
VisualStudio2017 VB言語で開発を行っております。
Socketで非同期受信を行い、データを受信した際イベントを発生し、
受信したデータをコピーする動作を行いたいのですが、RaiseEventを行った箇所でイベントが動作しません。
Socketのコネクションはできている状態で、データの受信もできておりました。
受信後の処理で、RaiseEventを入れていますが、Exceptionにも入らずそのまま通りてしまいます。
自分で調べた内容では、問題なくできているはずなのですが、Eventが発生しません。
参照が行われていないのでしょうか?
行き詰ったので質問させていただきます。
--- Main ---
Public WithEvents cls As SocketClass
Private receive_data As Byte()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
socket.SocketObject()
End Sub
Public Sub ReceiveData(ByVal obj As Object, ByVal e As ReceiverEventArgs) Handles cls.ReceiveData
receive_data = e.myReceiverData
End Sub
--- SocketClass ---
Public Sub SocketObject()
ip_end = New IPEndPoint(IPAddress.Parse(remote_IP), remote_Port)
soc_obj = New Socket(ip_end.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
Receive(soc_obj)
End Sub
'ステータスオブジェクト
Public Class StatusObject
Public workSocket As Socket = Nothing
Public Const bufferSize As Integer = 1000000
Public buffer As Byte() = New Byte(bufferSize) {}
Public sb As StringBuilder = New StringBuilder()
End Class
'非同期での受信を開始
Private Sub Receive(ByVal soc As Socket)
Try
Dim state As StatusObject = New StatusObject()
state.workSocket = soc
soc.BeginReceive(state.buffer, 0, StatusObject.bufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), tate)
Catch ex As Exception
End Try
End Sub
'非同期受信のコールバック
Private Sub ReceiveCallback(ByVal ar As IAsyncResult)
Try
Dim state As StatusObject = ar.AsyncState
Dim Client As Socket = state.workSocket
Dim bytesRead = state.workSocket.EndReceive(ar)
Dim recdata As Byte() = New Byte(bytesRead) {}
If bytesRead > 0 Then
Dim test As ReceiverEventArgs = New ReceiverEventArgs(state.buffer, state.buffer.Length - 1)
RaiseEvent ReceiveData(Me, test)
Client.BeginReceive(state.buffer, 0, StatusObject.bufferSize, 0, New AsyncCallback(AddressOf eceiveCallback), state)
Else
If state.sb.Length > 1 Then
response = state.sb.ToString()
End If
receive_Done.Set()
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
--- オブジェクト作成クラス ---
Public Class ReceiverEventArgs
Public myReceiverData() As Byte
Private m_size As Integer = 0
Public ReadOnly Property Size()
Get
Return m_size
End Get
End Property
Public Sub New(ByVal bytReceiverData() As Byte, ByVal size As Integer)
CopyByte(bytReceiverData, size) 'Copy Data
End Sub
Private Function CopyByte(ByVal bytReceiverData() As Byte, ByVal size As Integer) As Boolean
Dim i As Integer 'for Loop
Try
If (size <= 0) Then size = 1
ReDim myReceiverData(size - 1)
For i = 0 To size - 1
myReceiverData(i) = bytReceiverData(i)
Next
m_size = size 'Save Size
Return True
Catch ex As Exception
Return False
End Try
End Function
End Class
|