190930
This commit is contained in:
83
Pilz.Networking/TCPManager.vb
Normal file
83
Pilz.Networking/TCPManager.vb
Normal 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
|
||||
Reference in New Issue
Block a user