How do i send messages from one computer to another using vb.net?

久未见 提交于 2019-12-05 15:06:05

Using TcpClient and related libraries is definitely the correct answer.

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

Use TcpListener for watching for incoming data.

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!