Files
Pilz/Pilz.IO/ManagedPipes/ManagedPipeClient.vb

92 lines
2.6 KiB
VB.net

Imports System.Net
Imports System.Text
Imports System.IO.Pipes
Imports Pilz.Threading
Public Class ManagedPipeClient : Inherits ManagedPipe
Private pipeStream As PipeStream
Private _Buf(&H400 - 1) As Byte
Public Property RaiseEventsGui As Boolean = True
Public Sub New(pipeName As String)
Me.New(pipeName, ".")
End Sub
Public Sub New(pipeName As String, serverName As String)
Me.New(pipeName, serverName, -1)
End Sub
Public Sub New(pipeName As String, connectionTimeout As Integer)
Me.New(pipeName, ".", connectionTimeout)
End Sub
Public Sub New(pipeName As String, serverName As String, connectionTimeout As Integer)
Dim clnt As New NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)
clnt.Connect(connectionTimeout)
If Not clnt.IsConnected Then
Throw New TimeoutException("Connection timeout!")
End If
SetPipe(clnt)
End Sub
Public Sub New(pipe As PipeStream)
SetPipe(pipe)
End Sub
Private Sub SetPipe(pipe As PipeStream)
pipeStream = pipe
pipeStream.BeginRead(_Buf, 0, _Buf.Length, AddressOf EndRead, Nothing)
End Sub
Private Sub EndRead(ar As IAsyncResult)
If IsDisposed Then Return
Dim bytesCount As Integer = pipeStream.EndRead(ar)
If bytesCount = 0 Then 'leere Datenübermittlung signalisiert Verbindungsabbruch
If RaiseEventsGui Then
CrossThreadsInvokeing.RunGui(AddressOf Dispose)
Else
Dispose()
End If
Return
End If
Dim list As New List(Of Byte)
For i As Integer = 0 To bytesCount - 1
list.Add(_Buf(i))
Next
Do While bytesCount = _Buf.Length
bytesCount = pipeStream.Read(_Buf, 0, _Buf.Length)
For i As Integer = 0 To bytesCount - 1
list.Add(_Buf(i))
Next
Loop
Dim deargs As New DataEventArgs(list.ToArray)
If RaiseEventsGui Then
CrossThreadsInvokeing.RunGui(AddressOf OnRetriveData, deargs)
Else
OnRetriveData(deargs)
End If
pipeStream.BeginRead(_Buf, 0, _Buf.Length, AddressOf EndRead, Nothing)
End Sub
Public Overrides Function SendAsnyc(bytes() As Byte) As Task
Return Task.Run(Sub() Send(bytes))
End Function
Public Overrides Sub Send(data As Byte())
pipeStream.Write(data, 0, data.Length)
End Sub
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
pipeStream.Dispose()
End Sub
End Class