1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Public UDPCli As UdpClient
Public UDPSer As UdpClient
Public Start As Boolean = False
' Démarre le serveur
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Start = True
Button2.Enabled = False
Button3.Enabled = True
Dim th As New Threading.Thread(AddressOf Serveur) : th.Start()
End Sub
' Arrêt du serveur (du thread)
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Start = False
End Sub
' Serveur sur un nouveau Thread
Public Sub Serveur()
While Start = True
Try
UDPSer = New UdpClient(11) ' Bind sur le port 11
UDPSer.Client.ReceiveTimeout = 1000
Dim recu As Byte() = UDPSer.Receive(New IPEndPoint(IPAddress.Parse("127.0.0.1"), 11)) ' Attente d'un message sur le port 11
MsgBox(Encoding.UTF8.GetString(recu))
Catch ex As Exception
' Timeout
End Try
UDPSer.Close()
End While
Me.Invoke(Sub() Button2.Enabled = True)
Me.Invoke(Sub() Button3.Enabled = False)
End Sub
' Envoi d'un message "Hello"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
UDPCli = New UdpClient()
UDPCli.Connect(New IPEndPoint(IPAddress.Parse("127.0.0.1"), 11))
Dim send As Byte() = Encoding.UTF8.GetBytes("Hello!")
UDPCli.Send(send, send.Length)
UDPCli.Close()
End Sub
End Class |