Imports System.Net.Sockets
Imports System.Net
Imports System.Threading
Imports System.IO

Public Class NetworkStringConnection1
    Dim Listener As TcpListener
    Dim Client As TcpClient
    WithEvents Timer As New System.Windows.Forms.Timer
    Public Event StringArrived(ByVal ArrivedString As String, ByVal SenderIPAddress As String)

    Private Function GetInternetIP()
        Dim W As New WebClient
        Return W.DownloadString("http://ip.mcandy007.de")
    End Function

    Private Function GetNetworkIP()
        Dim LocalHostName As String = Dns.GetHostName()
        Dim ipEnter As IPHostEntry = Dns.GetHostByName(LocalHostName)
        Dim IpAdd() As IPAddress = ipEnter.AddressList
        Return IpAdd(0).ToString
    End Function

    Public Sub New(Optional ByVal Port As Integer = 51252)
        Listener = New TcpListener(Port)
    End Sub

    Private Sub Listening()
        Try
            Listener.Start()
        Catch ex As Exception

        End Try

    End Sub

    Public Sub Start()
        Dim Listthread As New Thread(New ThreadStart(AddressOf Listening))
        Listthread.Start()
        Timer.Interval = 1
        Timer.Start()
    End Sub

    Public Sub Close()
        Listener.Stop()
    End Sub

    Public Function SendString(ByVal Message As String, ByVal IPAddress As String, Optional ByVal Port As Integer = 55) As String
        Dim SenderIP As String = Nothing

        If IPAddress.StartsWith("192.168.") Or IPAddress = "127.0.0.1" Then
            SenderIP = GetNetworkIP()
        Else
            SenderIP = GetInternetIP()
        End If

        Try
            Client = New TcpClient(IPAddress, Port)
            Dim writer As New StreamWriter(Client.GetStream())
            writer.Write(SenderIP & "|" & Message)
            writer.Flush()
            Return Nothing
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function

    Private Sub Timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer.Tick
        Try
            If Listener.Pending = True Then
                Client = Listener.AcceptTcpClient()
                Dim ArrivedString As String = Nothing
                Dim reader As New StreamReader(Client.GetStream())
                Try
                    While reader.Peek > -1
                        ArrivedString += Convert.ToChar(reader.Read()).ToString
                    End While
                    Dim Pos As Integer = InStr(ArrivedString, "|")
                    Dim SenderIP As String = Mid(ArrivedString, 1, Pos - 1)
                    Dim Message As String = Mid(ArrivedString, Pos + 1)
                    RaiseEvent StringArrived(Message, SenderIP)
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            Else : End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class
