更新时间:2022-12-23 21:53:25
使用TcpClient和相关库绝对是正确的答案.
Using TcpClient and related libraries is definitely the correct answer.
用于将数据写入特定IP/端口的示例代码:
Sample code for writing data to a specific IP/port:
''' <summary>
''' Send data over TCP/IP network
''' </summary>
''' <param name="data">Data string to write</param>
''' <param name="IP">The connected destination TcpClient</param>
Public Sub WriteData(ByVal data As String, ByRef IP As String)
Console.WriteLine("Sending message """ & data & """ to " & IP)
Dim client As TcpClient = New TcpClient()
client.Connect(New IPEndPoint(IPAddress.Parse(IP), My.Settings.CommPort))
Dim stream As NetworkStream = client.GetStream()
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes(data)
stream.Write(sendBytes, 0, sendBytes.Length)
End Sub
使用TcpListener监视传入的数据.
Use TcpListener for watching for incoming data.
http://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcplistener.aspx
为了知道将其发送到哪个IP ...您可以具有要连接到的内部IP列表,或者可以将每台联网计算机订阅"到您的程序中(如果它们静态地托管在一个盒子上).就我的目的而言,当我使用此代码时,主机进程位于一台已知的服务器上.想要接收消息的客户端进程向主机发送一条快速消息,然后主机将记录该IP以供以后发送.
edit: For knowing what IP to send it to... You could either have a list of internal IPs to connect to, or have each networked computer 'subscribe' to your program if it's hosted statically on a box. For my purposes, when I'm using this code, the host process sits on a known server. Client processes that want to receive messages sends a quick message to the host, which will then record the IP to be able to send to later.
获得请求客户端的IP:
Obtaining the IP of a requesting client:
''Given variable m_listener is an active TcpListener...
Dim client As TcpClient = m_listener.AcceptTcpClient()
Dim requesterIP As String = client.Client.RemoteEndPoint.ToString().Split(New Char() {":"})(0)