-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathUdpChat.ps1
75 lines (65 loc) · 1.82 KB
/
UdpChat.ps1
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# A simple .Net based UDP Chat
#
param( $address="Loopback", $lPort=2020, $rPort=2020 )
route print 0* |
%{
if( $_ -match "\s{2,}0\.0\.0\.0" )
{
$null,$null,$null,$LocalIP,$null = [regex]::replace($_.trimstart(" "),"\s{2,}",",").split(",")
}
}
try{
$localEndpoint = new-object System.Net.IPEndPoint( [IPAddress]::Any, $lPort )
$udpReceiver = new-object System.Net.Sockets.UdpClient $lPort
$remoteEndpoint = new-object System.Net.IPEndPoint( [IPAddress]::$address, $rPort )
$udpSender = new-object System.Net.Sockets.UdpClient
}
catch{
throw $_
exit -1
}
$data = ""
$dataReady = $false
while( $Host.UI.RawUi.KeyAvailable )
{ $Host.UI.RawUI.FlushInputBuffer() }
Write-Host "Press ESC to stop the udp chat ..." -fore yellow
Write-Host ""
Write-Host -NoNewLine ":> "
while( $true )
{
if( $Host.UI.RawUi.KeyAvailable )
{
$key = $Host.UI.RawUI.ReadKey( "NoEcho,IncludeKeyDown,IncludeKeyUp" )
$Host.UI.RawUI.FlushInputBuffer()
if( $key.VirtualKeyCode -eq 27 )
{ break }
elseif( $key.VirtualKeyCode -eq 13 )
{
$dataReady = $true
$null = $Host.UI.RawUI.ReadKey().Character
$Host.UI.RawUI.FlushInputBuffer()
}
else
{
#$data += $key.Character
$data += $Host.UI.RawUI.ReadKey().Character
$Host.UI.RawUI.FlushInputBuffer()
}
}
if( $udpReceiver.Available )
{
$content = $udpReceiver.Receive( [ref]$localEndpoint )
Write-Host "`n$($localEndpoint.Address.IPAddressToString):$($localEndpoint.Port) $([Text.Encoding]::ASCII.GetString($content))"
Write-Host -NoNewLine ":> "
}
if( $dataReady )
{
Write-Host -NoNewLine "`n:> "
$bytes = [Text.Encoding]::ASCII.GetBytes( $data )
$bytesSent = $udpSender.Send( $bytes, $bytes.length, $remoteEndpoint )
$data = ""
$dataReady = $false
}
}
$udpSender.Close( )
$udpReceiver.Close( )