|
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class Form1
' スレッドの終了をコントロールするフラグ
Private stopFlg As Integer = 0
Private UdpClient As New UdpClient(11001)
' ************************************************************
' 初期処理
' ************************************************************
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
' 受信タイムアウト( 送信サイクルの倍 )
UdpClient.Client.ReceiveTimeout = 2000
' スレッド処理するメソッドを作成
Dim ThreadProc As New Thread(AddressOf ThreadEntry)
' スレッド開始
ThreadProc.Start()
End Sub
' ************************************************************
' スレッドの入り口
' ************************************************************
Private Sub ThreadEntry()
Dim Bridge As New ProcBridge(AddressOf SetData)
' 参照する為に、常に 0 で比較後等しければ 0 をセット。1 の時にループ終了
Do While Interlocked.CompareExchange(stopFlg, 0, 0) = 0
Thread.Sleep(1000)
Console.WriteLine(Now)
Me.Invoke(Bridge, New Object() {1, Now.ToString()})
Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 11000)
Try
' このへんは、MSDN そのまま
Dim receiveBytes As Byte() = UdpClient.Receive(RemoteIpEndPoint)
Dim returnData As String = Encoding.ASCII.GetString(receiveBytes)
Console.WriteLine(returnData.ToString())
Console.WriteLine(("address:" + RemoteIpEndPoint.Address.ToString() + _
"、port:" + RemoteIpEndPoint.Port.ToString()))
Me.Invoke(Bridge, New Object() {2, returnData.ToString() + "/" + _
RemoteIpEndPoint.Address.ToString()})
Catch e As Exception
Console.WriteLine(e.ToString())
End Try
Loop
' 実際の終了を通知する
Me.Invoke(Bridge, New Object() {-1, "終了処理中です..."})
End Sub
' ************************************************************
' 橋渡し用デリゲート
' ************************************************************
Delegate Sub ProcBridge(ByVal type As Integer, ByVal str As String)
' ************************************************************
' 橋渡し用実体
' ************************************************************
Private Sub SetData(ByVal type As Integer, ByVal str As String)
If type = 1 Then
Me.TextBox1.Text = str
End If
If type = 2 Then
Me.TextBox2.Text = str
End If
If type = -1 Then
Me.TextBox2.Text = str
' 強制描画
Me.TextBox2.Update()
Thread.Sleep(1000)
' 終了通知うけて、実際終了する
' ( FormClosing と FormClosed が発生する )
Application.Exit()
End If
End Sub
' ************************************************************
' フォームが閉じる前( e.Cancel = True でキャンセル可能 )
' ************************************************************
Private Sub Form1_FormClosing(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles MyBase.FormClosing
' スレッド実行中ならば、スレッドが終了する状態にして、終了処理をキャンセル
If Interlocked.CompareExchange(stopFlg, 0, 0) = 0 Then
Interlocked.Exchange(stopFlg, 1)
e.Cancel = True
End If
End Sub
End Class
| |