【发布时间】:2023-01-30 21:08:07
【问题描述】:
在 Windows 10 上,我想从 UDP 端口 9001 读取数据。我创建了以下不提供任何输出的脚本(python 3.10.9):
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", 9001))
while True:
data, addr = sock.recv(1024)
print(f"received message: {data.decode()} from {addr}")
我检查了一个设备正在使用端口 9001 发送 UDP 数据线鲨.但是上面的代码只是在 powershell 上“运行”,没有任何输出(也没有任何错误)。
任何想法如何解决这一问题?
我找到了this page电源外壳应该侦听 UDP 端口的脚本。所以我尝试了这个并创建了一个文件Start-UDPServer.ps1,其内容如下所述:
function Start-UDPServer {
[CmdletBinding()]
param (
# Parameter help description
[Parameter(Mandatory = $false)]
$Port = 10000
)
# Create a endpoint that represents the remote host from which the data was sent.
$RemoteComputer = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, 0)
Write-Host "Server is waiting for connections - $($UdpObject.Client.LocalEndPoint)"
Write-Host "Stop with CRTL + C"
# Loop de Loop
do {
# Create a UDP listender on Port $Port
$UdpObject = New-Object System.Net.Sockets.UdpClient($Port)
# Return the UDP datagram that was sent by the remote host
$ReceiveBytes = $UdpObject.Receive([ref]$RemoteComputer)
# Close UDP connection
$UdpObject.Close()
# Convert received UDP datagram from Bytes to String
$ASCIIEncoding = New-Object System.Text.ASCIIEncoding
[string]$ReturnString = $ASCIIEncoding.GetString($ReceiveBytes)
# Output information
[PSCustomObject]@{
LocalDateTime = $(Get-Date -UFormat "%Y-%m-%d %T")
SourceIP = $RemoteComputer.address.ToString()
SourcePort = $RemoteComputer.Port.ToString()
Payload = $ReturnString
}
} while (1)
}
并开始它电源外壳终端(作为管理员)作为
.\Start-UDPServer.ps1 -Port 9001
它立即返回到 Powershell,没有任何输出(或错误消息)。也许窗户坏了?
如果有最终监听UDP 9001端口的方案,我还是强烈推荐一个Python解决方案!
【问题讨论】:
-
您是否检查过系统上的防火墙是否阻止了流量?
标签: python windows powershell