-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSockets.ps1
61 lines (55 loc) · 1.75 KB
/
Sockets.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
function Host-Server {
param(
[String]$Server = 'localhost',
[Int]$Port = '7777',
[ScriptBlock]$OnData = {},
[ScriptBlock]$OnChunk = {},
[ScriptBlock]$OnDisconnect = {}
)
$tcpConnection = New-Object System.Net.Sockets.TcpClient($Server, $Port)
$tcpStream = $tcpConnection.GetStream()
$reader = New-Object System.IO.StreamReader($tcpStream)
$writer = New-Object System.IO.StreamWriter($tcpStream)
$writer.AutoFlush = $true
while ($tcpConnection.Connected) {
[String[]]$Chunk = @()
while ($tcpStream.DataAvailable) {
$Chunk += $data = $reader.ReadLine()
$OnData.invoke($data)
}
$OnChunk.invoke($Chunk)
}
$OnDisconnect.invoke()
$reader.Close()
$writer.Close()
$tcpConnection.Close()
}
function Client-Server {
param (
[String]$Server = 'localhost',
[Int]$Port = '7777',
[ScriptBlock]$OnData = {},
[ScriptBlock]$OnChunk = {},
[ScriptBlock]$OnDisconnect = {}
)
[System.Net.Sockets.TcpClient] $tcpClient = [System.Net.Sockets.TcpClient]::new("localhost", "50001")
$tcpStream = $tcpClient.GetStream()
[System.IO.StreamReader] $reader = [System.IO.StreamReader]::new($tcpStream)
[System.IO.StreamWriter] $writer = [System.IO.StreamWriter]::new($tcpStream)
$writer.AutoFlush = $true
return [PSCustomObject]@{
Listen = Value
}
while ($tcpClient.Connected) {
[String[]]$Chunk = @()
while ($tcpStream.DataAvailable) {
$Chunk += $data = $reader.ReadLine()
$OnData.invoke($data)
}
$OnChunk.invoke($Chunk)
}
$OnDisconnect.invoke()
$reader.Close()
$writer.Close()
$tcpConnection.Close()
}