This commit is contained in:
2019-09-30 16:18:53 +02:00
parent 7d884d7cba
commit 53f2a0666b
70 changed files with 2984 additions and 197 deletions

View File

@@ -0,0 +1,84 @@
Imports System.IO
Imports Newtonsoft.Json.Linq
Public MustInherit Class ConnectionManagerBase
Private listening As Boolean = False
Public ReadOnly Property Port As Integer
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]()
Public MustOverride Sub Send(empfängerIP As String, cmd As String, content As Object)
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
Public Sub RaiseRetriveData(senderIP As String, cmd As String, content As Object)
RaiseEvent RetriveData(Me, senderIP, cmd, content)
End Sub
Protected Shared Function EncodeToBytes(cmd As String, content As Object) 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") = 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
End Class

View File

@@ -0,0 +1,13 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>false</MySubMain>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>1</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>

View File

@@ -0,0 +1,35 @@
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' Allgemeine Informationen über eine Assembly werden über die folgenden
' Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
' die einer Assembly zugeordnet sind.
' Werte der Assemblyattribute überprüfen
<Assembly: AssemblyTitle("Pilz.Networking")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("DRSN")>
<Assembly: AssemblyProduct("Pilz.Networking")>
<Assembly: AssemblyCopyright("Copyright © DRSN 2019")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird.
<Assembly: Guid("467b9a06-75bf-4894-b88d-397eeb2bb0cc")>
' Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
'
' Hauptversion
' Nebenversion
' Buildnummer
' Revision
'
' Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
' übernehmen, indem Sie "*" eingeben:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>

View File

@@ -0,0 +1,62 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Pilz.Networking.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,73 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Pilz.Networking.My.MySettings
Get
Return Global.Pilz.Networking.My.MySettings.Default
End Get
End Property
End Module
End Namespace

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" UseMySettingsClassName="true">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@@ -0,0 +1,54 @@
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Public Module NetworkFeatures
Public Function GetIPFromHost(hostName As String) As IPAddress
Return Dns.GetHostAddresses(hostName).FirstOrDefault(Function(n) n.AddressFamily = AddressFamily.InterNetwork)
End Function
Public Function GetHostFromIP(ip As String)
Return Dns.GetHostEntry(ip)?.HostName
End Function
Public Function GetLocalIPInformations() As UnicastIPAddressInformation
Dim addr As UnicastIPAddressInformation = Nothing
For Each adapter As NetworkInterface In NetworkInterface.GetAllNetworkInterfaces
If addr Is Nothing AndAlso adapter.OperationalStatus = OperationalStatus.Up AndAlso adapter.NetworkInterfaceType <> NetworkInterfaceType.Tunnel AndAlso adapter.NetworkInterfaceType <> NetworkInterfaceType.Loopback Then
For Each uni As UnicastIPAddressInformation In adapter.GetIPProperties.UnicastAddresses
If addr Is Nothing AndAlso uni.Address.AddressFamily = AddressFamily.InterNetwork Then
addr = uni
End If
Next
End If
Next
Return addr
End Function
Public Function GetLocalIPAddress() As IPAddress
Return GetLocalIPInformations()?.Address
End Function
Public Function GetLocalIPv4Mask() As IPAddress
Return GetLocalIPInformations()?.IPv4Mask
End Function
Public Function GetLocalBoradcastIP(ipInfo As UnicastIPAddressInformation) As IPAddress
Dim ip As IPAddress = Nothing
Dim myIPBytes As Byte() = ipInfo.Address.GetAddressBytes
Dim subnetBytes As Byte() = ipInfo.IPv4Mask.GetAddressBytes
Dim broadcastBytes As Byte() = New Byte(myIPBytes.Length - 1) {}
For i As Integer = 0 To subnetBytes.Length - 1
broadcastBytes(i) = myIPBytes(i) Or Not subnetBytes(i)
Next
ip = New IPAddress(broadcastBytes)
Return ip
End Function
End Module

View File

@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4584B121-09C6-40AC-849B-7E410125EF66}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Pilz.Networking</RootNamespace>
<AssemblyName>Pilz.Networking</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>Pilz.Networking.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>Pilz.Networking.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\..\ConsoleApp2\packages\System.ValueTuple.4.5.0\lib\netstandard1.0\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
<Import Include="System.Xml.Linq" />
<Import Include="System.Threading.Tasks" />
</ItemGroup>
<ItemGroup>
<Compile Include="ConnectionManagerBase.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="NetworkFeatures.vb" />
<Compile Include="TCPManager.vb" />
<Compile Include="UDPManager.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project>

View File

@@ -0,0 +1,83 @@
Imports System.IO
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports Newtonsoft.Json.Linq
Public Class TCPManager
Inherits ConnectionManagerBase
Private ReadOnly listener As TcpListener
Public Property BufferSize As Integer = 10240
Public Sub New(port As Integer)
MyBase.New(port)
listener = New TcpListener(IPAddress.Any, port)
End Sub
Public Overrides Sub Start()
If Not IsListening Then
listener.Start()
IsListening = True
Task.Run(AddressOf CheckRetriveData)
End If
End Sub
''' <summary>
''' Stop listening on given port.
''' </summary>
Public Overrides Sub [Stop]()
If IsListening Then
IsListening = False
listener.Stop()
End If
End Sub
Private Sub CheckRetriveData()
Do While IsListening
If listener.Pending Then
Dim tcp As TcpClient = listener.AcceptTcpClient()
Dim ip As String = CType(tcp.Client.RemoteEndPoint, IPEndPoint).Address.ToString
Dim Stream As NetworkStream = tcp.GetStream
Dim buf As Byte() = New Byte(BufferSize - 1) {}
tcp.ReceiveBufferSize = BufferSize
Stream.Read(buf, 0, buf.Length)
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
tcp.Close()
RaiseRetriveData(ip, cmd, content)
End If
Loop
End Sub
Public Overrides Sub Send(empfängerIP As String, cmd As String, content As Object)
Dim ep As New IPEndPoint(GetIPFromHost(empfängerIP).MapToIPv4, Port)
Dim tcp As New TcpClient
tcp.SendBufferSize = BufferSize
tcp.Connect(ep)
Dim stream As NetworkStream = tcp.GetStream()
Dim buf As Byte() = EncodeToBytes(cmd, content)
'Send Data
stream.Write(buf, 0, buf.Length)
stream.Flush()
tcp.Client.Shutdown(SocketShutdown.Both)
tcp.Close()
End Sub
End Class

View File

@@ -0,0 +1,94 @@
Imports System.IO
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports System.Threading
Imports Newtonsoft.Json.Linq
Public Class UDPManager
Inherits ConnectionManagerBase
Private ReadOnly client As UdpClient
Private listenTask As Task = Nothing
Private ReadOnly cancelTokenSource As New CancellationTokenSource
Private ReadOnly cancelToken As CancellationToken = cancelTokenSource.Token
Public Sub New(port As Integer)
MyBase.New(port)
client = New UdpClient(port)
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
client.Client.Shutdown(SocketShutdown.Both)
client.Close()
End Sub
Public Overrides Sub Start()
If Not IsListening Then
StartInternal()
End If
End Sub
Private Sub StartInternal()
IsListening = True
listenTask = Task.Run(
Sub()
Try
RetriveAnyData(cancelToken)
Catch ex As Exception
IsListening = False
End Try
End Sub)
End Sub
''' <summary>
''' Stop listening on given port.
''' </summary>
Public Overrides Sub [Stop]()
If IsListening Then
IsListening = False
cancelTokenSource.Cancel()
listenTask.Wait()
End If
End Sub
Private Sub RetriveAnyData(ct As CancellationToken)
Dim doExit = Sub() ct.ThrowIfCancellationRequested()
Dim receiveTask As Task(Of UdpReceiveResult) = client.ReceiveAsync()
'Wait for the data and cancel if requested
receiveTask.Wait(ct)
Dim buf As Byte() = receiveTask.Result.Buffer
Dim ip As String = receiveTask.Result.RemoteEndPoint.Address.ToString
Dim cmd As String = String.Empty
Dim content As Object = Nothing
doExit()
Try
Dim res = DecodeFromBytes(buf)
cmd = res.cmd
content = res.content
Catch ex As Exception
End Try
RaiseRetriveData(ip, cmd, content)
doExit()
StartInternal()
End Sub
Public Overrides Sub Send(empfängerIP As String, cmd As String, content As Object)
Dim ep As New IPEndPoint(GetIPFromHost(empfängerIP).MapToIPv4, Port)
Dim udp As New UdpClient
Dim buf As Byte() = EncodeToBytes(cmd, content)
udp.Connect(ep)
udp.Send(buf, buf.Length)
udp.Client.Shutdown(SocketShutdown.Both)
udp.Close()
End Sub
End Class

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="12.0.2" targetFramework="net45" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net45" />
</packages>