我有一个在VB.NET中创建的WinForm应用程序,我需要在接收UDP消息的同一端口回答,但我运行的应用程序源端口的代码正由OS选择,或者它似乎是这样。
Private Sub UdpSend(ByVal txtMessage As String)
Dim pRet As Integer
GLOIP = IPAddress.Parse(IpRemotaLbl.Text)
GLOINTPORT = RemotePortLbl.Text
MyUdpClient.Connect(GLOIP, GLOINTPORT)
bytCommand = Encoding.ASCII.GetBytes(txtMessage)
pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
'Console.WriteLine("No of bytes send " & pRet)
PrintLog("No of bytes send " & pRet)
End Sub
例如,如果我在端口8082上收到UDP消息,则当前正在从端口1515(本地)向8082(远程)发送应答,我需要将消息从端口8082(本地)发送到8082(远程)。
感谢。
答案 0 :(得分:1)
在致电UdpClient
之前,您需要将Send()
绑定到本地端口。指定源端口的唯一方法是在UdpClient
的构造函数中,因此如果您在第一次收到消息之前不知道要使用哪个源端口,那么您必须等到创建UdpClient
。
Private Sub UdpSend(ByVal txtMessage As String)
Dim pRet As Integer
Dim MyUdpClient as UdpClient = new UdpClient(8082); ' <-- here
MyUdpClient.Connect(IPAddress.Parse(IpRemotaLbl.Text), RemotePortLbl.Text)
bytCommand = Encoding.ASCII.GetBytes(txtMessage)
pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
'Console.WriteLine("No of bytes send " & pRet)
PrintLog("No of bytes send " & pRet)
End Sub