Imports System.IO Imports System.Net Imports Newtonsoft.Json.Linq Public MustInherit Class ConnectionManagerBase Private listening As Boolean = False Public ReadOnly Property Port As Integer Public Property UseAssemblyQualifiedName As Boolean = False Public Event RetriveData(manager As ConnectionManagerBase, senderIP As String, cmd As String, content As Object) Public Property IsListening As Boolean Get Return listening End Get Protected Set(value As Boolean) listening = value End Set End Property Public Sub New(port As Integer) Me.Port = port End Sub Protected Overrides Sub Finalize() [Stop]() End Sub Public MustOverride Sub Start() Public MustOverride Sub [Stop]() Protected MustOverride Sub SendData(endPoint As IPEndPoint, data As Byte()) Public Overridable Sub Send(empfängerIP As String, cmd As String) Send(empfängerIP, cmd, String.Empty) End Sub Public Overridable Sub Send(empfängerIP As String, cmd As String, info As String) Send(empfängerIP, cmd, CObj(info)) End Sub Private Sub RaiseRetriveData(senderIP As String, cmd As String, content As Object) RaiseEvent RetriveData(Me, senderIP, cmd, content) End Sub Protected Sub ProcessRetrivedData(senderIP As String, buf As Byte()) Dim contentstring As String = Text.Encoding.Default.GetString(buf) Dim content As Object = Nothing Dim cmd As String = String.Empty Try Dim res = DecodeFromBytes(buf) cmd = res.cmd content = res.content Catch ex As Exception End Try RaiseRetriveData(senderIP, cmd, content) End Sub Protected Shared Function EncodeToBytes(cmd As String, content As Object, useAssemblyQualifiedName As Boolean) As Byte() Dim ms As New MemoryStream() Dim bw As New BinaryWriter(ms) Dim obj As New JObject 'Write header obj("Cmd") = cmd obj("ContentType") = If(useAssemblyQualifiedName, content?.GetType?.AssemblyQualifiedName, content?.GetType?.ToString) 'Content obj("Content") = JToken.FromObject(content) 'Write Json to MemoryStream bw.Write(Text.Encoding.Default.GetBytes(obj.ToString)) 'Get Buffer Bytes Dim buf As Byte() = ms.ToArray ms.Close() Return buf End Function Protected Shared Function DecodeFromBytes(buf As Byte()) As (cmd As String, content As Object) Dim contentstring As String = Text.Encoding.Default.GetString(buf) Dim content As Object = Nothing Dim contentobj As JObject = JObject.Parse(contentstring) Dim cmd As String = contentobj("Cmd") Dim contenttypestring As String = contentobj("ContentType") Dim contentlinq As JToken = contentobj("Content") If Not String.IsNullOrEmpty(contenttypestring) Then Dim contenttype As Type = Type.GetType(contenttypestring) content = contentlinq.ToObject(contenttype) End If Return (cmd, content) End Function Public Sub Send(empfängerIP As String, cmd As String, content As Object) Dim ep As New IPEndPoint(GetIPFromHost(empfängerIP).MapToIPv4, Port) Dim buf As Byte() = EncodeToBytes(cmd, content, UseAssemblyQualifiedName) SendData(ep, buf) End Sub End Class