Wednesday, December 26, 2007

UDP: Server receives packets from a client, then echoes packets back to clients | VB.Net

UDP: Server receives packets from a client, then echoes packets back to clients VB.Net



Imports System.Threading
Imports System.Net.Sockets
Imports System.IO
Imports System.Net


Public Class MainClass
Shared Dim client As UdpClient
Shared Dim receivePoint As IPEndPoint

Public Shared Sub Main()

client = New UdpClient(5000)

receivePoint = New IPEndPoint(New IPAddress(0), 0)

Dim readThread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets))

readThread.Start() ' wait for packets
End Sub

Shared Public Sub WaitForPackets()
While True
Dim data As Byte() = client.Receive(receivePoint)
Console.WriteLine("Packet received:" & _
vbCrLf & "Length: " & data.Length & vbCrLf & _
"Containing: " & _
System.Text.Encoding.ASCII.GetString(data) )

Console.WriteLine("Echo data back to client...")

client.Send(data, data.Length, receivePoint)
Console.WriteLine("Packet sent")
End While
End Sub

End Clas