====== TCPクライアント ======
[[:powershell|一つ上へ]]
$port = 9998
$target = "127.0.0.1" # 140.83.34.242
$buffer = Read-Host "Input"
# クライアント
$client = [System.Net.Sockets.TcpClient]::new()
try {
# ターゲットホストへの接続
Write-Host "Connect to $target : $port"
Write-Host "$buffer"
# バイト列に変換
$bytesSend = [System.Text.Encoding]::UTF8.GetBytes($buffer)
$client.Connect($target, $port)
$stream = $client.GetStream()
$stream.Write($bytesSend, 0, $bytesSend.Length)
# ターゲットホストからの接続を待機
$recv_len = 1
$response = ""
# 受信データがなくなるまでデータを受信する
$receiveBuffer = New-Object byte[] 4096
$byteRead = $stream.Read($receiveBuffer, 0, $receiveBuffer.Length)
$data = [System.Text.Encoding]::UTF8.GetString($receiveBuffer, 0, $byteRead)
Write-Host "Received: $data"
} catch {
Write-Host "Exception, Exitting."
} finally {
# 接続のクローズ処理
$stream.Close()
$client.Close()
}
===== 受け取り方 =====
try {
# ターゲットホストへの接続
$client.Connect($target, $port)
$stream = $client.GetStream()
$stream.Write($bytesSend, 0, $bytesSend.Length)
# 受信データがなくなるまで受信
$receiveBuffer = New-Object byte[] 4096
$responseBytes = New-Object System.Collections.Generic.List[byte]
while (($byteRead = $stream.Read($receiveBuffer, 0, $receiveBuffer.Length)) -gt 0) {
$responseBytes.AddRange([System.ArraySegment[byte]]::new($receiveBuffer, 0, $byteRead))
# 残りのデータがあるか判定
if (-not $stream.DataAvailable) { break }
}
# デコードして表示する
$response = [System.Text.Encoding]::UTF8.GetString($responseBytes.ToArray())
Write-Host "Received: $response"
} catch {
Write-Host "Exception, Exitting."
Write-Host "$_"
} finally {
# クローズ処理
if ($stream) {$stream.Close()}
if ($client) {$client.Close()}
}